2017-09-28 73 views
2

我有一個(法文)的數據集,看起來像文件作爲千分隔符如下:閱讀CSV與空間使用pandas.read_csv

time;col1;col2;col3 
06.09.2017 05:30;329,02;5,7;259 
06.09.2017 05:40;500,5;6,6;261 
06.09.2017 05:50;521,73;6,7;266 
06.09.2017 06:00;1 091,33;9,1;273 
06.09.2017 06:10;1 262,43;10;285 

我嘗試使用下面的命令來閱讀:

import pandas as pd 
df=pd.read_csv("Example_dataset.csv", 
      index_col=0, 
      encoding='latin', 
      parse_dates=True, 
      dayfirst=True, 
      sep=';', 
      decimal=',', 
      thousands=' ') 

col2和col3被識別爲浮點數和整數,但col1不會被識別爲數字,因爲數千個分隔符在那裏。有沒有簡單的方法來讀取這個數據集?設置thousands=' '似乎沒有工作:

<class 'pandas.core.frame.DataFrame'> 
DatetimeIndex: 5 entries, 2017-09-06 05:30:00 to 2017-09-06 06:10:00 
Data columns (total 3 columns): 
col1 5 non-null object 
col2 5 non-null float64 
col3 5 non-null int64 
dtypes: float64(1), int64(1), object(1) 
memory usage: 160.0+ bytes 

有什麼建議嗎?

+0

嘗試:'df.col1 = df.col1。 str.replace('','').astype(float)' –

+0

我剛剛測試了熊貓'0.20.1'並且你的代碼有效,你使用的是哪個版本? – zipa

+0

這沒有奏效。我認爲這個空間是一個'不間斷的空間' 我修改你的代碼如下: 'df.col1 = df.col1.str.replace('\ s +','').str.replace(', ','。')。astype(float)' – Nickj

回答

4

如果你有非換空間,我建議更積極的正則表達式與str.replace

df.col1 = df.col1.str.replace('[^\d.,e+-]', '')\ 
       .str.replace(',', '.').astype(float) 

正則表達式

[  # character group 
^  # negation - ignore everything in this character group 
\d  # digit 
.  # dot 
e  # 'e' - exponent 
+-  # signs 
]