How to extract dollar amount from pandas DataFrame column

匆匆过客 提交于 2021-02-08 14:49:34

问题


I would to get dollar amounts from more than hundreds rows in a column, and then save the amount in a new column. The dollar amount varies in each row, like $100.01, $1,000.05, 10,000, 100,000 etc.

One of the lines looks like this:

Approving the settlement claim of Mr. X Y by payment in the amount of $120,000.65

I tried to do something like this, but it's not extracting the dollar amount:

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

Please help.


回答1:


IIUC need:

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

EDIT:

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


来源:https://stackoverflow.com/questions/51905346/how-to-extract-dollar-amount-from-pandas-dataframe-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!