将货币转换为浮动(括号表示负数)

I a*_*rge 18 python currency pandas

我有货币的df:

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

     Currency
0       $1.00
1   $2,000.00
2  (3,000.00)
Run Code Online (Sandbox Code Playgroud)

我想将'Currency'dtype转换为float,但我遇到括号字符串(表示负数)的问题.这是我目前的代码:

df[['Currency']] = df[['Currency']].replace('[\$,]','',regex=True).astype(float)
Run Code Online (Sandbox Code Playgroud)

这会产生错误:

ValueError: could not convert string to float: (3000.00)
Run Code Online (Sandbox Code Playgroud)

我想要的dtype float是:

     Currency
0       1.00
1   2000.00
2  -3000.00
Run Code Online (Sandbox Code Playgroud)

Joh*_*hnE 33

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

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

   Currency
0         1
1      2000
2     -3000
Run Code Online (Sandbox Code Playgroud)