2015-07-20 33 views
13

我有貨幣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) 

我想將「貨幣」 D型浮動轉換,但我有括號字符串的麻煩(這表示負數)。這是我當前的代碼:

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

產生一個錯誤:

ValueError: could not convert string to float: (3000.00) 

我想要什麼作爲D型浮動是:

 Currency 
0  1.00 
1 2000.00 
2 -3000.00 

回答

25

只需添加)現有的命令,然後將(轉換爲-以使括號中的數字爲負數。然後轉換爲浮動。

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

    Currency 
0   1 
1  2000 
2  -3000 
+1

@George這裏你從JohnE那裏得到它。速度更快。 –

0

這就是,如果你想確保其加入,特別是如果你有很多它的平均數據幀中的列的數據幀,所以你可以在它的工作

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