【问题标题】:How to extract dollar amount from pandas DataFrame column如何从 pandas DataFrame 列中提取美元金额
【发布时间】:2019-01-25 02:01:12
【问题描述】:

我会从一列中的数百行中获取美元金额,然后将金额保存在新列中。每行的美元金额各不相同,例如 100.01 美元、1,000.05 美元、10,000 美元、100,000 美元等。

其中一行如下所示:

批准 X Y 先生支付 120,000.65 美元的和解索赔

我试图做这样的事情,但它没有提取美元金额:

df['amount'] = df['description'].str.extract('/(\$[0-9]+(\.[0-9]{2})?)/', expand=True)

请帮忙。

【问题讨论】:

  • 预期输出是什么?

标签: python regex python-3.x pandas


【解决方案1】:

IIUC 需要:

df=pd.DataFrame({'description':['ss $100.01', 'dd $1,000.05', 
                                'f 10,000', 'g 100,000',
                                'yr 4,120,000.65']})

df['amount'] = df['description'].str.extract('([0-9,.]+)')
print (df)
       description        amount
0       ss $100.01        100.01
1     dd $1,000.05      1,000.05
2         f 10,000        10,000
3        g 100,000       100,000
4  yr 4,120,000.65  4,120,000.65

编辑:

df['amount1'] = df['description'].str.extract('(\$[0-9,.]+)')
df['amount2'] = df['description'].str.extract('\$([0-9,.]+)')
print (df)

       description    amount1   amount2
0       ss $100.01    $100.01    100.01
1     dd $1,000.05  $1,000.05  1,000.05
2         f 10,000        NaN       NaN
3        g 100,000        NaN       NaN
4  yr 4,120,000.65        NaN       NaN

【讨论】:

  • @ScottBoston - 正则表达式对我来说很难,所以我想找到更好的解决方案;)
  • 如果行中有一些非美元的数字,比如案件编号等呢?
  • 所以只需要返回前 2 个值吗?
  • 还是需要加元输出?
  • 将美元添加到输出中。我认为这对我有用: str.extract('(\$[0-9,]+)' - 谢谢你的帮助。
猜你喜欢
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
相关资源
最近更新 更多