2017-02-24 94 views
1

我试着用下面的代码行来解决所需的任务:覆写楠与的.loc值熊猫

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

enter image description here

但是,这提出了一个“SettingWithCopyWarning”,我认为定位在数据框中使用.loc特性的Nan值(列'年龄')可能是更好的方法。

我已经看过documentation,但仍不知道如何解决这个问题。无法在.loc找到任何解决方案。

我会很感激任何提示和建议。

回答

1

您需要fillna用于替换NaN一些价值:与loc

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

您的解决方案:

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 
+0

非常感谢你的帮助。代码工作得很好。你能解释一下.loc函数中发生了什么?我最初认为它是用于访问诸如Age的索引。我们为什么要传递.isnan部分,然后又是Age列?真的很难理解这一点,即使在阅读文档之后。 – ErnieandBert

+0

好吧,它的工作原理是:np.isnan(df ['Age'])'返回布尔值掩码,并与'loc'组合值设置为'rand1',其中'True'值。我认为更好的解释是在这[熊猫教程](http://tomaugspurger.github.io/modern-1.html) - 检查标题'SettingWithCopy'(使用另一个掩码'f ['a'] <= 3'而不是'np.isnan(df ['Age'])') – jezrael

+0

本教程是[here](http://pandas.pydata.org/pandas-docs/stable/tutorials.html) - '现代熊猫'(非常好的解释) – jezrael