python - 将货币转换为 float (括号表示负数)

标签 python pandas currency

我有一个带有货币的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/

相关文章:

python - 列表理解头痛

python 多处理问题

python - 从延迟收集创建大型 dask.dataframe 时被杀死/内存错误

Python:大型数据集中分类值的卡方

python - 通过value_counts()将一个dataframe分成两个DF

c# - 我如何处理在 .NET 中使用多种货币的国家?

python - 查找数组中一行的最小或最大总和

python - 删除具有冲突标签的行

java - 金融应用程序中必需的货币数据类型?

javascript - toLocaleString 价格不带小数点零