python - 将字符串数字列转换为 Pandas 中的浮点数
问题描述
我想将以下数据框转换为price1
类型:price2
float
id price1 price2
0 1 9,771,338.7 NaN
1 2 9,734,256 NaN
2 3 3,331,766 2,391,766
3 4 2,414,571 1,856,571
4 5 725,031.33 NaN
5 6 1,530,519.75 1,392,519.75
6 7 4,655,184.06 NaN
7 8 9,864,973.6 8,224,973.6
8 9 14,599,046.08 9,514,046.08
9 10 2,075,439.87 1,259,439.87
我的第一个解决方案:
price_cols = ['price1', 'price2']
df[price_cols] = df[price_cols].astype(float)
出去:
ValueError: could not convert string to float: '9,771,338.7'
我的第二个解决方案:
df[price_cols] = df[price_cols].apply(pd.to_numeric, errors='coerce')
出去:
id price1 price2
0 1 NaN NaN
1 2 NaN NaN
2 3 NaN NaN
3 4 NaN NaN
4 5 NaN NaN
5 6 NaN NaN
6 7 NaN NaN
7 8 NaN NaN
8 9 NaN NaN
9 10 NaN NaN
我怎样才能正确转换这些列?谢谢。
解决方案
您的列包含无法解析为浮点数的逗号。只需在将它们转换为浮点数之前将它们从字符串中删除。
df['price1'] = df['price1'].str.replace(',', '').astype(float)
推荐阅读
- java - Unsafe 的方法 compareAndSwapObject 机制
- c++ - 如何有效缓解“周期偏差”
- python - 自托管 Sphinx 文档中的多个版本
- pandas - 如何在不写熊猫每个名字的情况下删除列?
- android - 通过命令行更改包名称(没有 Android Studio)
- ios - iOS - 组合 - 将发布者类型更改为子类型
- r - 如何计算与 R 中相同列值关联的两个行值的差异?
- windows-10 - AutoHotkey:在 Windows 10 中检测任务切换器窗口
- php - 如何使用 PHP 从字符串中获取特定的 html 元素
- kubernetes - KubernetesClientException - 操作获取失败