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

标签 python pandas

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

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/

相关文章:

python - 在 Windows 上嵌入 Python : why does it have to be a DLL?

python - 为什么 Pandas 绘制索引值 (x_ticklabels) 不正确?

python - 有条件地用 pandas 中的行值填充列

Python unittest 分支覆盖似乎错过了 zip 中执行的生成器

python - nosetests sqlalchemy 插件如何工作?

python - PANDAS - 将列表作为值的列转换为虚拟变量

python - 多索引数据透视表的 Pandas 减法

python - 读取多个数据时,根据列变量将提取的单元格(iloc)循环到列表中

python - 代理身份验证错误 - python

python - Azure Databricks 错误 : AzureException: hadoop_azure_shaded. com.microsoft.azure.storage.StorageException:服务器无法对请求进行身份验证