Python Pandas replace multiple columns zero to Nan

僤鯓⒐⒋嵵緔 提交于 2019-12-20 19:37:11

问题


List with attributes of persons loaded into pandas dataframe df2. For cleanup I want to replace value zero (0 or '0') by np.nan.

df2.dtypes

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

Working code to set value zero to 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

Believe this can be done in a similar/shorter way:

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

However the above does not work. The zero's remain in df2. How to tackle this?


回答1:


I think you need replace by dict:

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



回答2:


data['amount']=data['amount'].replace(0, np.nan)
data['duration']=data['duration'].replace(0, np.nan)


来源:https://stackoverflow.com/questions/45416684/python-pandas-replace-multiple-columns-zero-to-nan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!