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

25

我有一个带货币的数据框:

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
2个回答

47

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

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

   Currency
0         1
1      2000
2     -3000

1
@JohnE,如果我可以补充一下几乎完美的答案:df['Currency'].replace( '[\$,)]','', regex=True ).replace( '[(]','-', regex=True).replace( '[ ]+', 'NaN', regex=True).astype(float) - rohit_wason
@JohnE,抱歉我应该澄清一下,这将用“NaN”替换空白(任意数量的连续空格),因为空白会在.astype(float)处失败。 - rohit_wason
@rohit_wason 好的,明白了,这是个好点子。这里是你建议的代码稍微改动一下来处理空字符串的方式:(df['Currency'].replace( '[\$,) ]+','',regex=True ).replace( '[(]','-', regex=True ).replace( '', 'NaN', regex=True ).astype(float)) 如果你想要写出来,我会很乐意点赞。你可能还想添加一些额外的带有空格的行来进行演示。如果你不想,我可以将它添加到我的代码中,尽管我的代码现在有点古老,所以我不太愿意对其进行太多更改。 - JohnE

1
如果您希望确保它被添加到DataFrame中,请使用以下代码:df['Currency']=(df['Currency'].replace( '[\$,)]','', regex=True ) .replace( '[(]','-', regex=True ).astype(float))。该代码涉及货币和数据框的处理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接