我有一个带有货币的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)
我想将“货币”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
最佳答案
只需将)
添加到现有命令,然后将(
转换为-
,使括号中的数字变为负数。然后转换为float。
(df['Currency'].replace( '[\$,)]','', regex=True )
.replace( '[(]','-', regex=True ).astype(float))
Currency
0 1
1 2000
2 -3000
关于python - 将货币转换为 float (括号表示负数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31521526/