我有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列--DATE,TIME,SECONDS和NANOSECONDS。
我希望将文件读作pandas
DataFrame
,其中DATE,TIME和NANOSECONDS为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)
但这失败了,因为%f格式要求纳秒值有9位数而不是6位数。如果我手动从NANOSECONDS列中的值中删除3个额外的零,则上述代码有效。
您能否告诉我,如何使用DATE,TIME和NANOSECONDS列作为索引将示例文件作为pandas
DataFrame
对象读入?
[更新]如果NANOSECONDS列不包含0值,则behzad.nouri建议使用%f000
。所以,显然这就是导致问题的原因。
答案 0 :(得分:5)
使用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]
答案 1 :(得分:3)
尝试:
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位;