问题描述
我在数据框中有一个看起来像这样的列
Index Col
0 -1
1 2
2 -3
3 -
4 3
5 -
6 -7
如何在不将负值前面的减号更改为零的情况下,将用于表示Col(如索引3和5)中的空值的“-”替换为0。当前的dtype是object,我打算在处理完null值后将其更改为float。
解决方法
您可以像这样使用replace:
df.replace('-',0).astype(float)
输出:
Col
Index
0 -1.0
1 2.0
2 -3.0
3 0.0
4 3.0
5 0.0
6 -7.0
,
尝试一下
df[df.Col.eq('-')] = 0
print(df)
输出:
Col
0 -1
1 2
2 -3
3 0
4 3
5 0
6 -7
,
您可以简单地使用
df["Col"] = df.Col.str.replace('^-$','0')
print(df)