2017-02-14 93 views
1

我有一個大的數據框,大約100萬行和9列,有些行在一些列中缺少數據。Pandas Dataframe對象類型

dat = pd.read_table('file path', delimiter = ';') 

I  z  Sp S  B  B/T  r  gf  k 
0  0.0303 2 0.606 0.31  0.04 0.23  0.03 0.38 
1  0.0779 2    0.00  0.00 0.05  0.01 0.00 

前幾列以字符串形式讀入,最後幾列以NaN形式讀入,即使存在數值時也如此。當我包含dtype ='float64'時,我得到:

ValueError: could not convert string to float: 

任何幫助解決此問題?

+0

是每個值浮點數? – Ika8

+0

@ Ika8是的,他們是 – Cmf55

+0

嘗試與Dtype =對象 – Ika8

回答

1

您可以通過正則表達式使用replace - 一個或多個whitespacesNaN,然後轉換爲數據float

空字符串read_table轉換爲NaN

df = df.replace({'\s+':np.nan}, regex=True).astype(float) 
print (df) 
    I  z Sp  S  B B/T  r gf  k 
0 0.0 0.0303 2.0 0.606 0.31 0.04 0.23 0.03 0.38 
1 1.0 0.0779 2.0 NaN 0.00 0.00 0.05 0.01 0.00 

如果數據包含一些字符串這就需要及時更換,NaN是可能使用to_numericapply

df = df.apply(lambda x: pd.to_numeric(x, errors='coerce')) 
print (df) 
    I  z Sp  S  B B/T  r gf  k 
0 0 0.0303 2 0.606 0.31 0.04 0.23 0.03 0.38 
1 1 0.0779 2 NaN 0.00 0.00 0.05 0.01 0.00 
+0

它是如何工作的? – jezrael

+0

最後三列在NaN全部讀取時都被讀取爲全部值。它適用於前6。 – Cmf55

+0

您是否使用'df.replace({'\ s +':np.nan},regex = True).astype(float)'或'to_numeric'解決方案?最後3列中的數據是數字嗎? – jezrael