您需要fillna替换NaN为某些值:
df.Age = df.Age.fillna(rand1)
Run Code Online (Sandbox Code Playgroud)
您的解决方案loc:
df.loc[np.isnan(df["Age"]), 'Age'] = rand1
#same as
#df.loc[df["Age"].isnull(), 'Age'] = rand1
Run Code Online (Sandbox Code Playgroud)
您也可以检查索引视图与复制。
样品:
df = pd.DataFrame({'Age':[20,23,np.nan]})
print (df)
Age
0 20.0
1 23.0
2 NaN
rand1 = 30
df.Age = df.Age.fillna(rand1)
print (df)
Age
0 20.0
1 23.0
2 30.0
Run Code Online (Sandbox Code Playgroud)
#if need cast to int
df.Age = df.Age.fillna(rand1).astype(int)
print (df)
Age
0 20
1 23
2 30
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8296 次 |
| 最近记录: |