如何从导入的csv文件索引datetime列 - pandas

时间:2016-07-06 17:56:13

标签: csv datetime pandas indexing concatenation

我正在尝试合并&附加不同的时间序列,从csv文件导入它们。我尝试了以下基本代码:

import pandas as pd
import numpy as np
import glob
import csv
import os

path = r'./A08_csv'     # use your path
#all_files = glob.glob(os.path.join(path, "A08_B1_T5.csv"))

df5 = pd.read_csv('./A08_csv/A08_B1_T5.csv', parse_dates={'Date Time'})
df6 = pd.read_csv('./A08_csv/A08_B1_T6.csv', parse_dates={'Date Time'})

print len(df5)
print len(df6)

df = pd.concat([df5],[df6], join='outer')
print len(df)

结果是:

12755 (df5)
24770 (df6)
12755 (df)

只要这两个文件中最长的文件(根据['日期时间']栏中的值有很多共同的行),不应该df

我尝试根据日期时间索引数据,添加以下行:

#df5.set_index(pd.DatetimeIndex(df5['Date Time']))

但是我收到了错误:

KeyError: 'Date Time'

有关为何会发生这种情况的任何线索?

2 个答案:

答案 0 :(得分:1)

我认为你需要:

index_col

或更好read_csv添加参数import pandas as pd import io temp=u"""Date Time,a 2010-01-27 16:00:00,2.0 2010-01-27 16:10:00,2.2 2010-01-27 16:30:00,1.7""" df = pd.read_csv(io.StringIO(temp), index_col=['Date Time'], parse_dates=['Date Time']) print (df) a Date Time 2010-01-27 16:00:00 2.0 2010-01-27 16:10:00 2.2 2010-01-27 16:30:00 1.7 print (df.index) DatetimeIndex(['2010-01-27 16:00:00', '2010-01-27 16:10:00', '2010-01-27 16:30:00'], dtype='datetime64[ns]', name='Date Time', freq=None)

Date Time

另一种解决方案是按顺序添加到参数列 - 如果列0是第一个,则将index_col添加到parse_dates0(来自import pandas as pd import io temp=u"""Date Time,a 2010-01-27 16:00:00,2.0 2010-01-27 16:10:00,2.2 2010-01-27 16:30:00,1.7""" df = pd.read_csv(io.StringIO(temp), index_col=0, parse_dates=[0]) print (df) a Date Time 2010-01-27 16:00:00 2.0 2010-01-27 16:10:00 2.2 2010-01-27 16:30:00 1.7 print (df.index) DatetimeIndex(['2010-01-27 16:00:00', '2010-01-27 16:10:00', '2010-01-27 16:30:00'], dtype='datetime64[ns]', name='Date Time', freq=None) 的蟒蛇计数):

=Length*txtConversionFactor

答案 1 :(得分:0)

这是不正确的:

pd.concat([df5],[df6], join='outer')

concat的第二个参数是axis。相反,你想要:

pd.concat([df5, df6], join='outer')