Python Pandas将零列替换为Nan

问题描述:

列出了加载到熊猫数据框df2中的人员的属性的列表.为了进行清理,我想用np.nan替换零值(0'0').

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

将代码零值设置为np.nan的工作代码:

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)

但是以上方法不起作用.零保留在df2中.该如何解决?

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

我认为您需要