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

Convert currency to float (and parentheses indicate negative amounts)

我有一个带有货币的df:

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

     Currency
0       .00
1   ,000.00
2  (3,000.00)

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

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

产生错误:

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

我想要的 dtype float 是:

     Currency
0       1.00
1   2000.00
2  -3000.00

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

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

   Currency
0         1
1      2000
2     -3000

如果您想确保将其添加到 DataFrame 中,尤其是当您有很多普通 DataFrame 具有的列时,您可以处理它

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