2024-09-28 21:03:46 发布
网友
我试图用以下代码行解决所需的任务:
df['Age'][np.isnan(df["Age"])] = rand1
但这会引发一个“SettingWithCopyWarning”,我认为通过使用.loc功能定位数据帧(列“Age”)中的Nan值可能是更好的方法。
.loc
我已经看了一下documentation,但是仍然不知道如何解决这个问题。在这里也找不到任何关于.loc的解决方案。
我希望得到任何提示和建议。
需要^{}将NaN替换为某些值:
NaN
df.Age = df.Age.fillna(rand1)
使用loc的解决方案:
loc
df.loc[np.isnan(df["Age"]), 'Age'] = rand1 #same as #df.loc[df["Age"].isnull(), 'Age'] = rand1
您也可以检查indexing view versus copy。
样品:
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
#if need cast to int df.Age = df.Age.fillna(rand1).astype(int) print (df) Age 0 20 1 23 2 30
需要^{} 将
NaN
替换为某些值:使用
loc
的解决方案:您也可以检查indexing view versus copy。
样品:
相关问题 更多 >
编程相关推荐