gpt4 book ai didi

python - 如何在 Pandas 中将对象转换为 float ?

转载 作者:行者123 更新时间:2023-12-04 08:00:39 25 4
gpt4 key购买 nike

我将一个 csv 文件读入一个 Pandas 数据帧,并将所有列类型作为对象。我需要将第二列和第三列转换为 float 。
我尝试使用

df["Quantidade"] = pd.to_numeric(df.Quantidade, errors='coerce')
但得到了 NaN。
这是我的数据框。我是否需要在第三列中使用一些正则表达式来摆脱“R$”?
enter image description here

最佳答案

尝试这个:

# sample dataframe
d = {'Quantidade':['0,20939', '0,0082525', '0,009852', '0,012920', '0,0252'],
'price':['R$ 165.000,00', 'R$ 100.000,00', 'R$ 61.500,00', 'R$ 65.900,00', 'R$ 49.375,12']}
df = pd.DataFrame(data=d)
# Second column
df["Quantidade"] = df["Quantidade"].str.replace(',', '.').astype(float)

#Third column
df['price'] = df.price.str.replace(r'\w+\$\s+', '').str.replace('.', '')\
.str.replace(',', '.').astype(float)
输出:
Quantidade  price
0 0.209390 165000.00
1 0.008252 100000.00
2 0.009852 61500.00
3 0.012920 65900.00
4 0.025200 49375.12

关于python - 如何在 Pandas 中将对象转换为 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66493992/

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