gpt4 book ai didi

python - 处理各种货币字符串 pandas

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

我有几十万行具有多种不同货币形式的数据,一些示例是:

116,319,545 SAR
40,381,846 CNY
57,712,170 CNY
158,073,425 RUB2
0 MYR
0 EUR
USD 110,169,240

这些值被读入DataFrame,我不确定最好的方法(如果有预构建的方法?)是从所有可能的情况中获取整数值。数据中可能有更多货币。

目前我最好的方法是:

df1['value'].str.replace(r"[a-zA-Z,]",'').astype(int)

但是对于条目xxxx RUB2,这显然失败了。

编辑:

除了工作答案之外,预计货币也很重要 - 提取正则表达式为 ([A-Z]+\d*)

最佳答案

鉴于此 df

df=pd.DataFrame()
df["col"]=["116,319,545 SAR",
"40,381,846 CNY",
"57,712,170 CNY",
"158,073,425 RUB2",
"0 MYR",
"0 EUR",
"USD 110,169,240"]

删除逗号后可以使用正则表达式'(\d+)'来获取

df.col.str.replace(",","").str.extract('(\d+)').astype(int)
0
0 116319545
1 40381846
2 57712170
3 158073425
4 0
5 0
6 110169240

另一个更手动的解决方案是拆分替换

df.col.str.split(' ').apply(lambda d: pd.Series(int(x.replace(",","")) for x in d if x.replace(",","").isdigit()).item())

0 116319545
1 40381846
2 57712170
3 158073425
4 0
5 0
6 110169240

关于python - 处理各种货币字符串 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51138054/

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