将货币转换为浮点数(括号表示负数) [英] Convert currency to float (and parentheses indicate negative amounts)

查看:107
本文介绍了将货币转换为浮点数(括号表示负数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用货币的df:

I have a df with currency:

df = pd.DataFrame({'Currency':['$1.00','$2,000.00','(3,000.00)']})

     Currency
0       $1.00
1   $2,000.00
2  (3,000.00)

我想将'Currency'dtype转换为float,但是括号字符串(表示负数)有麻烦.这是我当前的代码:

I want to convert the 'Currency' dtype to float but I am having trouble with the parentheses string (which indicate a negative amount). This is my current code:

df[['Currency']] = df[['Currency']].replace('[\$,]','',regex=True).astype(float)

会产生错误:

ValueError: could not convert string to float: (3000.00)

我想要的dtype float是:

What I want as dtype float is:

     Currency
0       1.00
1   2000.00
2  -3000.00

推荐答案

只需将)添加到现有命令中,然后将(转换为-,以使括号中的数字为负.然后转换为浮点数.

Just add ) to the existing command, and then convert ( to - to make numbers in parentheses negative. Then convert to float.

(df['Currency'].replace( '[\$,)]','', regex=True )
               .replace( '[(]','-',   regex=True ).astype(float))

   Currency
0         1
1      2000
2     -3000

这篇关于将货币转换为浮点数(括号表示负数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆