我有以下数据框架:
EO EW Inc20 Inc100
bike 6 4.0 7 5
other 1 NaN 1 1我想将NaN值替换为零。我写了以下代码:
for column in df:
df.loc[df.isnull().any(axis=1), column] = 0
df它运行良好,并将NaN更改为零,但也更改了第一列的值。所以我得到了这个结果:
EO EW Inc20 Inc100
bike 6 4.0 7 5
other 0 0 1 1但我想要:
EO EW Inc20 Inc100
bike 6 4.0 7 5
other 1 0 1 1发布于 2020-07-03 08:45:34
如果只需要替换,如果存在一个缺失值,则用DataFrame.isna和sum创建计数缺失值的掩码,在DataFrame.loc中用fillna创建筛选器
print (df)
EO EW Inc20 Inc100
bike 6 4.0 7 5.0
other 1 NaN 1 NaN
other 1 NaN 1 1.0
m = df.isna().sum().eq(1)
df.loc[:, m] = df.loc[:, m].fillna(0)或仅为每个列缺少的值创建掩码,并在DataFrame.mask中替换
m = df.isna() & df.isna().sum().eq(1)
df = df.mask(m, 0)print (df)
EO EW Inc20 Inc100
bike 6 4.0 7 5.0
other 1 NaN 1 0.0
other 1 NaN 1 1.0因为DataFrame.fillna替换了所有缺失的值:
df1 = df.fillna(0)
print (df1)
EO EW Inc20 Inc100
bike 6 4.0 7 5.0
other 1 0.0 1 0.0
other 1 0.0 1 1.0发布于 2020-07-03 08:56:56
添加到jezrael的答案中,如果只想在一列中更改值
df['EW'].fillna(0, inplace=True)https://stackoverflow.com/questions/62711656
复制相似问题