首页 > 解决方案 > 如何使用 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:“系列”对象没有属性“浮动”

我应该怎么办?

标签: pythonpandascsv

解决方案


我在用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

推荐阅读