gpt4 book ai didi

python - 转换字符串数列以在Pandas中 float

转载 作者:行者123 更新时间:2023-12-01 12:02:26 25 4
gpt4 key购买 nike

我想将以下数据帧中的price1price2转换为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)

关于python - 转换字符串数列以在Pandas中 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60594412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com