在Pandas中用.loc覆盖Nan值

2024-09-28 21:03:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用以下代码行解决所需的任务:

df['Age'][np.isnan(df["Age"])] = rand1

enter image description here

但这会引发一个“SettingWithCopyWarning”,我认为通过使用.loc功能定位数据帧(列“Age”)中的Nan值可能是更好的方法。

我已经看了一下documentation,但是仍然不知道如何解决这个问题。在这里也找不到任何关于.loc的解决方案。

我希望得到任何提示和建议。


Tags: 数据方法代码dfagedocumentationnpnan
1条回答
网友
1楼 · 发布于 2024-09-28 21:03:46

需要^{}NaN替换为某些值:

df.Age = df.Age.fillna(rand1)

使用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

相关问题 更多 >