使用pandas读取带有timestamp列的csv

2024-04-27 16:53:21 发布

您现在位置:Python中文网/ 问答频道 /正文

执行时:

import pandas
x = pandas.read_csv('data.csv', parse_dates=True, index_col='DateTime', 
                                names=['DateTime', 'X'], header=None, sep=';')

使用这个data.csv文件:

1449054136.83;15.31
1449054137.43;16.19
1449054138.04;19.22
1449054138.65;15.12
1449054139.25;13.12

(第1列是一个UNIX时间戳,即自1970年1月1日起经过的秒数),当使用x.resample('15S')每隔15秒对数据重新采样时,会出现此错误:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex

就像“datetime”信息没有被解析一样:

                 X
DateTime      
1.449054e+09  15.31                
1.449054e+09  16.19
...

如何使用pandas模块导入日期存储为时间戳的.CSV?

然后,一旦我能够导入CSV,如何访问日期为2015-12-02 12:02:18的行?


Tags: csvimporttruepandasreaddatadatetimeindex
3条回答

您可以自己分析日期:

import time
import pandas as pd

def date_parser(string_list):
    return [time.ctime(float(x)) for x in string_list]

df = pd.read_csv('data.csv', parse_dates=[0],  sep=';', 
                 date_parser=date_parser, 
                 index_col='DateTime', 
                 names=['DateTime', 'X'], header=None)

结果是:

>>> df
                        X
DateTime                  
2015-12-02 12:02:16  15.31
2015-12-02 12:02:17  16.19
2015-12-02 12:02:18  19.22
2015-12-02 12:02:18  15.12
2015-12-02 12:02:19  13.12

使用to_datetime并传递unit='s'将单元解析为unix时间戳,这将更快:

In [7]:
pd.to_datetime(df.index, unit='s')

Out[7]:
DatetimeIndex(['2015-12-02 11:02:16.830000', '2015-12-02 11:02:17.430000',
               '2015-12-02 11:02:18.040000', '2015-12-02 11:02:18.650000',
               '2015-12-02 11:02:19.250000'],
              dtype='datetime64[ns]', name=0, freq=None)

计时

In [9]:

import time
%%timeit
import time
def date_parser(string_list):
    return [time.ctime(float(x)) for x in string_list]
​
df = pd.read_csv(io.StringIO(t), parse_dates=[0],  sep=';', 
                 date_parser=date_parser, 
                 index_col='DateTime', 
                 names=['DateTime', 'X'], header=None)
100 loops, best of 3: 4.07 ms per loop

以及

In [12]:
%%timeit
t="""1449054136.83;15.31
1449054137.43;16.19
1449054138.04;19.22
1449054138.65;15.12
1449054139.25;13.12"""
df = pd.read_csv(io.StringIO(t), header=None, sep=';', index_col=[0])
df.index = pd.to_datetime(df.index, unit='s')
100 loops, best of 3: 1.69 ms per loop

因此,在这个小数据集上使用to_datetime要快2倍多,我希望这比其他方法的伸缩性要好得多

我的解决方案与迈克的类似:

import pandas
import datetime
def dateparse (time_in_secs):    
    return datetime.datetime.fromtimestamp(float(time_in_secs))

x = pandas.read_csv('data.csv',delimiter=';', parse_dates=True,date_parser=dateparse, index_col='DateTime', names=['DateTime', 'X'], header=None)

out = x.truncate(before=datetime.datetime(2015,12,2,12,2,18))

相关问题 更多 >