[英]How do convert an entire column string to a float within a dataframe using pandas?
我的df中有一个名为size的列
df['Size']
0 19M
1 14
2 8.7
3 25
4 2.8M
5 5.6
我想删除本专栏中的所有M,所以我做了
df.Size.str.replace('M','')
它工作,但我也想将此列中的字符串转换为浮点数。
我试过df.Size.float.replace('M','')
但我得到这个错误:
AttributeError:'Series'对象没有属性'float'
我该怎么办?
我正在使用to_numeric
更新
pd.to_numeric(df.Size.replace('M','',regex=True),errors='coerce').fillna(df.Size)
Out[497]:
0 19
1 14k
2 8.7
3 25
4 2.8
5 5.6
Name: Size, dtype: object
检查转换只有单元格包含k仍然是str
类型,所有其他变为float
pd.to_numeric(df.Size.replace('M','',regex=True),errors='coerce').fillna(df.Size).apply(type)
Out[501]:
0 <class 'float'>
1 <class 'str'>
2 <class 'float'>
3 <class 'float'>
4 <class 'float'>
5 <class 'float'>
Name: Size, dtype: object
数据输入
df
Out[500]:
Size
0 19M
1 14k
2 8.7
3 25
4 2.8M
5 5.6
为安全起见,我们可以使用regex
删除所有字母:
df['Size'] = df['Size'].str.replace('([A-Za-z])', '', regex=True).astype(float)
print(df)
Size
0 19.0
1 14.0
2 8.7
3 25.0
4 2.8
5 5.6
6 201.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.