我有一个时间戳相当奇怪的ASCII
文件:
DATAH DATE TIME SECONDS NANOSECONDS D
DATA 2012-06-04 23:49:15 1338853755 700000000 0.00855577
DATA 2012-06-04 23:49:15 1338853755 800000000 0.00805482
DATA 2012-06-04 23:49:15 1338853755 900000000 -0.00537284
DATA 2012-06-04 23:49:16 1338853756 0 -0.0239447
时间戳基本上分为4列-日期,时间,秒和纳秒。我想将文件读取为pandas
DataFrame
,日期,时间和纳秒作为datetime
对象,用作索引:
import datetime as dt
import pandas as pd
parse = lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S %f')
df = pd.read_csv('data.txt', sep='t', parse_dates=[['DATE', 'TIME', 'NANOSECONDS']], index_col=0, date_parser=parse)
但是这失败了,因为纳秒值有9个数字,而不是%f格式要求的6个。如果我手动从NANOSECONDS列的值中删除3个额外的零,上面的代码就可以工作。你能告诉我,我如何读取样本文件作为pandas
DataFrame
对象使用日期,时间和纳秒列作为索引?
[UPDATE]按照behzad的建议使用%f000
。如果NANOSECONDS列不包含0值,则nouri工作。显然,这就是现在的问题所在。
这将比使用read_csv日期解析器进行此转换快得多。
In [6]: data = """DATAH DATE TIME SECONDS NANOSECONDS D
...: DATA 2012-06-04 23:49:15 1338853755 700000000 0.00855577
...: DATA 2012-06-04 23:49:15 1338853755 800000000 0.00805482
...: DATA 2012-06-04 23:49:15 1338853755 900000000 -0.00537284
...: DATA 2012-06-04 23:49:16 1338853756 0 -0.0239447"""
In [7]: df = read_csv(StringIO(data),sep='s+')
In [8]: df
Out[8]:
DATAH DATE TIME SECONDS NANOSECONDS D
0 DATA 2012-06-04 23:49:15 1338853755 700000000 0.008556
1 DATA 2012-06-04 23:49:15 1338853755 800000000 0.008055
2 DATA 2012-06-04 23:49:15 1338853755 900000000 -0.005373
3 DATA 2012-06-04 23:49:16 1338853756 0 -0.023945
[4 rows x 6 columns]
In [9]: df.dtypes
Out[9]:
DATAH object
DATE object
TIME object
SECONDS int64
NANOSECONDS int64
D float64
dtype: object
In [13]: pd.to_datetime(df['SECONDS']+df['NANOSECONDS'].astype(float)/1e9, unit='s')
Out[13]:
0 2012-06-04 23:49:15.700000
1 2012-06-04 23:49:15.800000
2 2012-06-04 23:49:15.900000
3 2012-06-04 23:49:16
dtype: datetime64[ns]
try:
parse = lambda x: dt.datetime.strptime(x + '0'*(29 - len(x)), '%Y-%m-%d %H:%M:%S %f000')
我认为:
def parse(t):
import re
t = re.sub('([0-9]*)$', lambda m: '0'*(9 - len(m.group(1))) + m.group(1), t)
return dt.datetime.strptime(t[:-3], '%Y-%m-%d %H:%M:%S %f')
更安全,因为它在数字前面加了零;基本上,它确保纳秒值有9位数字,然后去掉最后3位;