我有一个数据集 d
,其中包含不同形式的缺失值:
d = {'col1': [1, 2, '', 'N/A', 'unknown', None],
'col2': [3, 4, 'N/A', None, 'N/A_N/A', '']}
d = pd.DataFrame(data=d)
col1 col2
0 1 3
1 2 4
2 N/A
3 N/A None
4 unknown N/A_N/A
5 None
我想看看每一列实际上有多少个值是缺失的。因此我想将所有空格、n/a和未知值转换为None
。我尝试了这段代码并得到了以下结果:
d.replace(to_replace =['N/A', '', 'unknown', 'N/A_N/A'],
value = None)
col1 col2
0 1 3
1 2 4
2 2 4
3 2 None
4 2 None
5 None None
我不明白为什么
d.replace
会这样做,有没有更好的解决方案?我希望它像这样: col1 col2
0 1 3
1 2 4
2 None None
3 None None
4 None None
5 None None
np.NaN
替换原生的缺失值(然后,只需使用df.isna().sum()
)。 - nocibambi