python - 如何使用 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:“系列”对象没有属性“浮动”
我应该怎么办?
解决方案
我在用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
推荐阅读
- r - 我正在 R 中构建一个闪亮的应用程序并不断收到“二进制运算符的非数字参数”的错误
- python - TimeDistributed(BatchNormalization)与 BatchNormalization
- java - Android Java onCreate
- c# - String.Split() 方法:编译器选择了错误的重载
- r - Dplyr:使用因子级别重命名小标题输出列
- r - 在特定轴刻度上应用粗体字
- javascript - 我的列表的 setValue 未使用当前值更新后的 setItem
- python - 导入前在 pytest 中打补丁
- python - 从 subprocess.run 使用“./”运行二进制文件
- flutter - Flutter如何在flutter中显示列表--每行2个项目