python - 如何从 pandas DataFrame 列中提取美元金额

标签 python regex python-3.x pandas

我想从一列中的数百行中获取美元金额,然后将金额保存在新列中。每行的美元金额各不相同,例如 $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)

请帮忙。

最佳答案

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

关于python - 如何从 pandas DataFrame 列中提取美元金额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51905346/

相关文章:

python - 如何在 Pandas 中连接可变数量的列

Python __add__ 整数魔术方法

Javascript 替换字符串中的文本

javascript - 从扩展对象javascript创建 key 对对象

python - 如何在库函数中使用异步事件循环

python - 如何使用 Python 3 HTTP 库创建 HTTP 代理处理程序

python-3.x - Elastic Beanstalk CLI 部署 zip 错误

python - 如何在Heroku上安装python opencv?

python - 多重引用嵌套列表

PHP:正则表达式、preg_split