python - Pandas Dataframe 中的缺失值填写错误

标签 python pandas dataframe

假设“df”是数据框对象,“ca”是变量之一。

>>> df.ca.value_counts()
0.0    176
1.0     65
2.0     38
3.0     20
?        4
Name: ca, dtype: int64

如您所见,我有四个缺失值。我想填写它们。使用下面的代码:

>>> df.loc[df.ca == '?', 'ca'] = 0.0
0.0    176
1.0     65
2.0     38
3.0     20
0.0      4
Name: ca, dtype: int64

为什么我有 5 个唯一值?我想将第五行合并到第一行,即

0.0   176 + 4 = 180
1.0     65
2.0     38
3.0     20

如何修复它?

最佳答案

因为 '?' 是您的值之一,我知道 df.cadtype object字符串。当您 replace('?', 0.) 时,您现在同时拥有字符串 '0.0' 和 float 0.0。将全部转换为 float 后,就不会有问题了。

df.ca.replace('?', 0.).astype(float).value_counts()

0.0    180
1.0     65
2.0     38
3.0     20
dtype: int64

关于python - Pandas Dataframe 中的缺失值填写错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39051292/

相关文章:

python - 基于字符串创建新列

r - 根据两个字符列之间的差异创建 R data.frame 列

python - Pandas 中的数据处理

dataframe - 如何在Spark SQL中重命名列名称

python - Django:如何使按钮在按下后消失/禁用?

python - 是否可以使用 matplotlib 在单独的窗口中显示多个图?

python - 修改pandas中的nan索引

python - 指示 GET 响应已通过 Python AppEngine 完成

Python 路径分隔符

python - 修改 Pandas 每小时时间轴上的刻度数