2017-02-12 43 views
1

我有,簡化的CSV文件,如下所示:pandas.read_csv:我如何在分層索引CSV中將兩列解析爲日期時間?

X,,Y,,Z, 
Date,Time,A,B,A,B 
2017-01-21,01:57:49.390,0,1,2,3 
2017-01-21,01:57:50.400,4,5,7,9 
2017-01-21,01:57:51.410,3,2,4,1 

前兩米欄是日期和時間。當我做」

pandas.read_csv('foo.csv', header=[0,1]) 

我得到以下數據框:

  X Unnamed: 1_level_0 Y Unnamed: 3_level_0 Z Unnamed: 5_level_0 
     Date    Time A     B A     B 
0 2017-01-21  01:57:49.390 0     1 2     3 
1 2017-01-21  01:57:50.400 4     5 7     9 
2 2017-01-21  01:57:51.410 3     2 4     1 

忽略列中煩人的不願透露姓名的條目現在,我想前兩列合併成一個單一的日期時間。所以,我嘗試使用parse_dates參數:

pandas.read_csv('foo.csv', header=[0,1], parse_dates={'datetime': [0,1]}) 

但所有我從這個得到的是一個回溯:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 646, in parser_f 
    return _read(filepath_or_buffer, kwds) 
    File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 401, in _read 
    data = parser.read() 
    File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 939, in read 
    ret = self._engine.read(nrows) 
    File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 1585, in read 
    names, data = self._do_date_conversions(names, data) 
    File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 1364, in _do_date_conversions 
    self.index_names, names, keep_date_col=self.keep_date_col) 
    File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 2737, in _process_date_conversion 
    data_dict.pop(c) 
KeyError: "('X', 'Date')" 

我不確定爲什麼它會在('X', 'Date')上打KeyError,因爲那些列肯定存在。我不知道這是否是我應該報告的pandas中的一個錯誤(我正在使用0.19.2),或者如果我只是不理解某些內容。有任何想法嗎?

+0

yup,看起來像一個錯誤。我使用了各種選項,在你的情況下可能效果最好的是將索引0和1指定爲索引,並將索引解析爲日期,即。 'pd.read_csv('foo.csv',header = [0,1],parse_dates = True,index_cols [0,1])''。報告這個問題將是一個好主意。 –

+0

我已爲此問題提交了PR。看到我的答案。 –

+1

更新:PR已批准發佈'0.20.0' –

回答

1

如果需要,您可以解決:

import datetime as dt 
import pandas as pd 

# read in the csv file 
df = pd.read_csv('foo.csv', header=[0, 1]) 

# get a label for the funky column names 
date_label, time_label = tuple(df.columns.values)[0:2] 

# merge the columns into a single datetime 
dates = [ 
    dt.datetime.strptime('T'.join(ts) + '000', '%Y-%m-%dT%H:%M:%S.%f') 
    for ts in zip(df[date_label], df[time_label])] 

# save the new column 
df['DateTime'] = pd.Series(dates).values 

更新:

我已經提交了bug並針對此問題的pull request。在response的bug中,jreback(熊貓首席維護者)對該示例中的多級頭的問題給出了相當詳細的回答。我認爲你已經意識到這些問題,但你可能想要閱讀他寫的內容。在響應結束時,他有一點可以提供解決方法:

製作單個級別在多級框架中沒有用。我可能會這樣做:

In [25]: pandas.read_csv(StringIO(data), header=0, skiprows=1, parse_dates={'datetime':[0,1]}) 
Out[25]: 
       datetime A B A.1 B.1 
0 2017-01-21 01:57:49.390 0 1 2 3 
1 2017-01-21 01:57:50.400 4 5 7 9 
2 2017-01-21 01:57:51.410 3 2 4 1