在熊猫中使用.loc覆盖Nan值

Ern*_*ert 3 python nan loc pandas

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

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

在此处输入图片说明

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

我已经看过文档,但是仍然不知道如何解决此问题。在此处找不到任何解决方案.loc

我将不胜感激任何提示和建议。

jez*_*ael 5

您需要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)