在 Pandas 数据框中填充缺失值错误。

3
假设'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

我该怎么修复它?
2个回答

1
因为您的值之一是'?',我知道df.cadtypeobjectstring。当您使用replace('?', 0.)时,现在有字符串'0.0'和浮点数0.0。将所有内容转换为浮点数后,您不应该遇到问题。
df.ca.replace('?', 0.).astype(float).value_counts()

0.0    180
1.0     65
2.0     38
3.0     20
dtype: int64

0
以下方法也基本可行:
In [193]: df = pd.DataFrame({'ca': [0.0]*176 + [1.0]*65 + [2.0]*38 + [3.0]*20 + ['?']*4})

In [194]: df.ca.value_counts()
Out[194]: 
0.0    176
1.0     65
2.0     38
3.0     20
?        4
Name: ca, dtype: int64

In [195]: df.loc[df.ca == '?', 'ca'] = 0.0

In [196]: df.ca.value_counts()
Out[196]: 
0.0    180
1.0     65
2.0     38
3.0     20
Name: ca, dtype: int64

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接