Pandas:read_csv,索引中只有HH:MM:SS

时间:2015-11-17 11:46:33

标签: python datetime pandas

我收到了这些数据:

Time;Flare;Praia;Spot2;Ruido
17:10:08.325;1.04;1.066;1.068;1.05
17:10:09.326;1.036;1.059;1.069;1.051
17:10:10.327;1.038;1.061;1.077;1.063
17:10:11.328;1.033;1.055;1.068;1.051

我使用以下方式阅读文件:

df = pd.read_csv(path + 'prueba.txt', sep=';',index_col=0,infer_datetime_format=True,
                       names=['time','flare','praia','spot','ruido'],header=1)

结果是

              flare  praia   spot  ruido
time                                    
17:10:09.326  1.036  1.059  1.069  1.051
17:10:10.327  1.038  1.061  1.077  1.063
17:10:11.328  1.033  1.055  1.068  1.051
17:10:12.329  1.041  1.057  1.075  1.049

您可以注意到索引时间没有日期(仅HH:MM:SS),结果索引不是日期时间类型。

type(df.index)
pandas.core.index.Index

我尝试使用pd.to_datetime但没有成功。 如果我必须添加日期,怎么办呢?

1 个答案:

答案 0 :(得分:1)

要获取DatetimeIndex,请使用parse_dates=[0]

df = pd.read_csv('data', sep=';',
                 names=['time','flare','praia','spot','ruido'], header=1,
                 index_col=0, parse_dates=[0])

产量

In [45]: df
Out[45]: 
                         flare  praia   spot  ruido
time                                               
2015-11-17 17:10:09.326  1.036  1.059  1.069  1.051
2015-11-17 17:10:10.327  1.038  1.061  1.077  1.063
2015-11-17 17:10:11.328  1.033  1.055  1.068  1.051

In [46]: df.index
Out[46]: 
DatetimeIndex(['2015-11-17 17:10:09.326000', '2015-11-17 17:10:10.327000',
               '2015-11-17 17:10:11.328000'],
              dtype='datetime64[ns]', name=u'time', freq=None, tz=None)

请注意,默认情况下会提供当前日期。

要获取TimedeltaIndex,您可以省略parse_dates参数并稍后转换HH:MM:SS字符串:

df = pd.read_csv('data', sep=';',
                 names=['time','flare','praia','spot','ruido'], header=1,
                 index_col=0)
df.index = pd.TimedeltaIndex(df.index)

产量

In [54]: df
Out[54]: 
                 flare  praia   spot  ruido
17:10:09.326000  1.036  1.059  1.069  1.051
17:10:10.327000  1.038  1.061  1.077  1.063
17:10:11.328000  1.033  1.055  1.068  1.051

In [55]: df.index
Out[55]: TimedeltaIndex(['17:10:09.326000', '17:10:10.327000', '17:10:11.328000'], dtype='timedelta64[ns]', freq=None)