gpt4 book ai didi

python - 将多个值替换为 Pandas 中的缺失值(无)

转载 作者:太空狗 更新时间:2023-10-30 02:51:41 26 4
gpt4 key购买 nike

我有一个数据集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

最佳答案

This is known behaviour并在目标替换值为 None 时发生。可以说,状态设计是参数处理方式的结果。

我可以建议 to_numeric 吗?

pd.to_numeric(df.stack(), errors='coerce').unstack()

col1 col2
0 1.0 3.0
1 2.0 4.0
2 NaN NaN
3 NaN NaN
4 NaN NaN
5 NaN NaN

或者,如果您将字典传递给 replace,您的代码就可以工作。

# df.replace({'': None, 'N/A': None, 'N/A_N/A': None, 'unknown': None})
df.replace(dict.fromkeys(['N/A', '', 'unknown', 'N/A_N/A'], None))

col1 col2
0 1.0 3.0
1 2.0 4.0
2 NaN NaN
3 NaN NaN
4 NaN NaN
5 NaN NaN

关于python - 将多个值替换为 Pandas 中的缺失值(无),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54831879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com