2017-06-06 50 views
0
import pandas as pd  
df = pd.DataFrame([["one", 1.2, "", "4,3"], 
    ["two","1,7", "2,4", 0.55], 
    ["three","", 5.4, "3,9"]], 
    columns=['a','b','c','d']) 

我如何可以替換列中的逗號b鍵d至點,使這些列的數字? 列(或任意數量的前導列的)應當保留不變(可以包含逗號爲好)替換逗號小數點的數據幀列,使其數字

回答

2
import re  

for col in ['b', 'c', 'd']: 
    df[col] = pd.to_numeric(df[col].apply(lambda x: re.sub(',', '.', str(x)))) 
+0

謝謝,這將完成這項工作:for col in df.columns [6:]: – ronnydw

0

你可以試試這個:

df = df.set_index('a') 
df.apply(lambda x: x.str.replace(',','.')).combine_first(df).apply(lambda x:pd.to_numeric(x,errors='coerce')).reset_index() 

輸出:

 a b c  d 
0 one 1.2 NaN 4.30 
1 two 1.7 2.4 0.55 
2 three NaN 5.4 3.90 

列A逗號測試

df = pd.DataFrame([["one", 1.2, "", "4,3"], 
    ["two","1,7", "2,4", 0.55], 
    ["three","", 5.4, "3,9"], 
    ["comma, here","2,1",1.2,""]], 
    columns=['a','b','c','d']) 

df = df.set_index('a') 
df2 = df.apply(lambda x: x.str.replace(',','.')).combine_first(df).apply(lambda x:pd.to_numeric(x,errors='coerce')).reset_index() 

print(df2) 

      a b c  d 
0   one 1.2 NaN 4.30 
1   two 1.7 2.4 0.55 
2  three NaN 5.4 3.90 
3 comma, here 2.1 1.2 NaN 
+0

列a應該保留並保持不變(也可以包含逗號) – ronnydw

+0

實際上我需要的是更復雜一些,前n列是文本,應該保持不變。其餘列應該轉換爲數字,但有些單元格使用「,」作爲小數點。 – ronnydw

+0

爲這個小問題,但它的工作原理,但正如我所說我的問題是更通用的,有幾列在DataFrame的fornt需要保持不變。最重要的是,這個解決方案看起來相當複雜,看似簡單的問題 – ronnydw

相關問題