2017-02-24 55 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