我有一个带货币的数据框:
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”数据类型转换为浮点数,但在括号字符串(表示负数金额)方面遇到了问题。这是我的当前代码:
df[['Currency']] = df[['Currency']].replace('[\$,]','',regex=True).astype(float)
导致错误的代码:
ValueError: could not convert string to float: (3000.00)
我想要的数据类型是float:
Currency
0 1.00
1 2000.00
2 -3000.00
df['Currency'].replace( '[\$,)]','', regex=True ).replace( '[(]','-', regex=True).replace( '[ ]+', 'NaN', regex=True).astype(float)
- rohit_wason.astype(float)
处失败。 - rohit_wason(df['Currency'].replace( '[\$,) ]+','',regex=True ).replace( '[(]','-', regex=True ).replace( '', 'NaN', regex=True ).astype(float))
如果你想要写出来,我会很乐意点赞。你可能还想添加一些额外的带有空格的行来进行演示。如果你不想,我可以将它添加到我的代码中,尽管我的代码现在有点古老,所以我不太愿意对其进行太多更改。 - JohnE