首页 > 解决方案 > 将字符串数字列转换为 Pandas 中的浮点数

问题描述

我想将以下数据框转换为price1类型:price2float

   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

我怎样才能正确转换这些列?谢谢。

标签: pythonpandasdataframe

解决方案


您的列包含无法解析为浮点数的逗号。只需在将它们转换为浮点数之前将它们从字符串中删除。

df['price1'] = df['price1'].str.replace(',', '').astype(float)

推荐阅读