pandas 将货币转换为浮动(括号表示负数)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31521526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert currency to float (and parentheses indicate negative amounts)
提问by I am not George
I have a df with currency:
我有一个带货币的 df:
df = pd.DataFrame({'Currency':['.00',',000.00','(3,000.00)']})
Currency
0 .00
1 ,000.00
2 (3,000.00)
I want to convert the 'Currency' dtype to float but I am having trouble with the parentheses string (which indicate a negative amount). This is my current code:
我想将 'Currency' dtype 转换为 float 但我在处理括号字符串(表示负数)时遇到问题。这是我当前的代码:
df[['Currency']] = df[['Currency']].replace('[$,]','',regex=True).astype(float)
which produces an error:
这会产生一个错误:
ValueError: could not convert string to float: (3000.00)
What I want as dtype float is:
我想要的 dtype float 是:
Currency
0 1.00
1 2000.00
2 -3000.00
回答by JohnE
Just add )to the existing command, and then convert (to -to make numbers in parentheses negative. Then convert to float.
只需添加)到现有的命令,然后转换(到-使括号负数。然后转换为浮动。
(df['Currency'].replace( '[$,)]','', regex=True )
.replace( '[(]','-', regex=True ).astype(float))
Currency
0 1
1 2000
2 -3000
回答by Redz Ch
this is if you want to make sure its added to the DataFrame especially if you have lots of columns which the average DataFrame has so you can work on it
这是如果您想确保将其添加到 DataFrame 中,特别是如果您有许多平均 DataFrame 具有的列,那么您可以对其进行处理
df['Currency']=(df['Currency'].replace( '[\$,)]','', regex=True )
.replace( '[(]','-', regex=True ).astype(float))
df['Currency']=(df['Currency'].replace( '[\$,)]','', regex=True )
.replace( '[(]','-', regex=True ).astype(float))

