我正在使用来自Kaggle的泰坦尼克号数据集,我试图用30替换NA值,当Pclass为2时。我尝试了下面的代码,但值30似乎没有保存在数据框中。
data[data['Pclass']==2].fillna({'Age':30}, inplace = True)
预期结果应该是Pclass = 2中的所有NA值将被30替换。但是当我再次检查时,我仍然看到NA值。
data[data['Pclass']==2]
输出为什么inplace = True不允许我在原始数据框中保存替换的值?
正如@sygneto所提到的,您正在将na填充到数据的子集中-它不会触及原始数据。当你得到警告SettingWithCopyWarning:试图在DataFrame的切片副本上设置值。
我会亲自找到我想要更新的列,并以列为基础进行更新。比如:
data.loc[(data['Pclass']==2) & (data['Age'].isnull()),'Age']=30
如果你正在复制,使用inplace和loc,创建新的var,然后使用inplace,一般以后不要使用inplace
df=data.loc[data['Pclass']==2]
df.fillna({'Age':30}, inplace = True)