gpt4 book ai didi

python - 如何将数据框中的符号转换为 python 中的 float ?

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:14 25 4
gpt4 key购买 nike

我是 python 的新手,正在研究字符串操作

我有一个数据框

df['Installs']
Out[22]:
0 10,000+
1 500,000+
2 5,000,000+
3 50,000,000+
4 100,000+
5 50,000+

如何删除“+”并将 df 中的字符串转换为 float ?

我的输入:

df['Installs'] = df['Installs'].str.replace('+','',regex=True).astype(float)

但是我得到一个错误:

ValueError: could not convert string to float: '10,000'

我如何编辑我的代码,使我得到 10,000.0 作为我的输出等其他值而不是 10,000+

最佳答案

使用Series.str.replace,+ 来清空 string:

df['Installs'] = df['Installs'].str.replace('[,+]','').astype(float)
#alternative
#df['Installs'] = df['Installs'].replace('[,+]','', regex=True).astype(float)
print (df)
Installs
0 10000.0
1 500000.0
2 5000000.0
3 50000000.0
4 100000.0
5 50000.0

关于python - 如何将数据框中的符号转换为 python 中的 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55746054/

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