2017-07-31 54 views
1

列出加載到熊貓數據框'df2'中的人的屬性。爲了清理,我想用np.nan替換零值(0或'0')。Python Pandas將多列零替換爲南

df2.dtypes 

ID     object 
Name     object 
Weight    float64 
Height    float64 
BootSize    object 
SuitSize    object 
Type     object 
dtype: object 

工作代碼設定值爲零np.nan:

df2.loc[df2['Weight'] == 0,'Weight'] = np.nan 
df2.loc[df2['Height'] == 0,'Height'] = np.nan 
df2.loc[df2['BootSize'] == '0','BootSize'] = np.nan 
df2.loc[df2['SuitSize'] == '0','SuitSize'] = np.nan 

相信這可以用類似的/短的方式進行:

df2[["Weight","Height","BootSize","SuitSize"]].astype(str).replace('0',np.nan) 

然而上述不起作用。零點保持在df2。如何解決這個問題?

回答

5

我想你需要通過replacedict

cols = ["Weight","Height","BootSize","SuitSize","Type"] 
df2[cols] = df2[cols].replace({'0':np.nan, 0:np.nan}) 
+0

完美的作品。謝謝! –

+0

很高興能幫到你,祝你好運! – jezrael