我有一个包含多个列的csv文件,其中一个是日期,下一个是时间,然后有一个像这样的毫秒:
DATE TIME MSEC
0 13/01/2017 08:49:37 805102
1 13/01/2017 08:49:09 675839
2 13/01/2017 08:39:03 50614
3 13/01/2017 08:38:30 383081
现在我印象深刻的是我可以使用pandas来结合读取csv文件时的日期和时间,如
pd.read_csv(r"~/file.csv", parse_dates=[["DATE","TIME"]])
但我似乎也无法在毫秒内挤压。由于文件非常大,如果可以在read_csv中完成,而不是在连续步骤中完成,我会很高兴。
答案 0 :(得分:1)
更新:在阅读CSV时动态解析不同列中的日期:
In [181]: pd.read_csv(fn,
date_parser=lambda d,t,ms: d + ' ' + t + '.' + ms,
parse_dates={'Timestamp':['DATE','TIME','MSEC']})
Out[181]:
Timestamp
0 2017-01-13 08:49:37.805102
1 2017-01-13 08:49:09.675839
2 2017-01-13 08:39:03.506140
3 2017-01-13 08:38:30.383081
OLD回答:
首先按原样阅读您的CSV:
df = pd.read_csv(r"~/file.csv")
In [170]: df
Out[170]:
DATE TIME MSEC
0 13/01/2017 08:49:37 805102
1 13/01/2017 08:49:09 675839
2 13/01/2017 08:39:03 50614
3 13/01/2017 08:38:30 383081
In [171]: df.dtypes
Out[171]:
DATE object
TIME object
MSEC int64
dtype: object
现在我们可以转换它:
In [172]: df['TimeStamp'] = pd.to_datetime(df.DATE + ' ' + df.TIME + '.' + df.MSEC.astype(str), format='%d/%m/%Y %H:%M:%S.%f')
In [173]: df
Out[173]:
DATE TIME MSEC TimeStamp
0 13/01/2017 08:49:37 805102 2017-01-13 08:49:37.805102
1 13/01/2017 08:49:09 675839 2017-01-13 08:49:09.675839
2 13/01/2017 08:39:03 50614 2017-01-13 08:39:03.506140
3 13/01/2017 08:38:30 383081 2017-01-13 08:38:30.383081
In [174]: df.dtypes
Out[174]:
DATE object
TIME object
MSEC int64
TimeStamp datetime64[ns]
dtype: object
<强>时序:强>
In [186]: df = pd.concat([df] * 10**3, ignore_index=True)
In [187]: df.shape
Out[187]: (4000, 3)
In [188]: df.to_csv(fn, index=False)
In [189]: pd.options.display.max_rows = 6
In [190]: df
Out[190]:
DATE TIME MSEC
0 13/01/2017 08:49:37 805102
1 13/01/2017 08:49:09 675839
2 13/01/2017 08:39:03 50614
... ... ... ...
3997 13/01/2017 08:49:09 675839
3998 13/01/2017 08:39:03 50614
3999 13/01/2017 08:38:30 383081
[4000 rows x 3 columns]
In [191]: %%timeit
...: pd.read_csv(fn,
...: date_parser=lambda d,t,ms: d + ' ' + t + '.' + ms,
...: parse_dates={'Timestamp':['DATE','TIME','MSEC']})
...:
1 loop, best of 3: 3.31 s per loop
In [192]: %%timeit
...: df = pd.read_csv(fn)
...: df['TimeStamp'] = pd.to_datetime(df.pop('DATE') + ' ' +
...: df.pop('TIME') + '.' +
...: df.pop('MSEC').astype(str),
...: format='%d/%m/%Y %H:%M:%S.%f')
...:
10 loops, best of 3: 122 ms per loop
结论:按原样读取CSV,从DataFrame解析日期的速度是4.000行数据集的27倍。