我有一个DataFrame,类似于:
DF = {'Col': [1, 2, 3,...,100, 10-1 , 10-2]}
我想去掉最后两行的"-“字。如果我使用replace on列,则得到没有"-“的值的NaN。
例如:
DF['Col'] = DF['Col'].str.replace('-','')
在以下方面的成果:
DF = {'Col': [NAN, NAN, NAN,...,NAN, 101 , 102]}
是否有一种方法可以删除"-“,而不必在其他行上获得NaN?
发布于 2022-01-14 16:47:54
您的问题是因为存在整数值和字符串的混合。首先将整个列转换为字符串:
>>> df['Col'].astype(str).str.replace('-', '')
0 1
1 2
2 3
3 100
4 101
5 102
Name: Col, dtype: object
# Without cast
>>> df['Col'].str.replace('-', '')
0 NaN
1 NaN
2 NaN
3 NaN
4 101
5 102
Name: Col, dtype: object
显然,现在您可以还原它并将您的列转换为int:
>>> df['Col'].astype(str).str.replace('-', '').astype(int)
0 1
1 2
2 3
3 100
4 101
5 102
Name: Col, dtype: int64
https://stackoverflow.com/questions/70713699
复制相似问题