日期时间字符串的基数并不大。例如,格式中的时间字符串数%H-%M-%S
为24 * 60 * 60 = 86400
. 如果您的数据集的行数远大于此,或者您的数据包含大量重复的时间戳,则在解析过程中添加缓存可以大大加快速度。
对于那些没有 Cython 可用的人,这里有一个纯 python 的替代解决方案:
import numpy as np
import pandas as pd
from datetime import datetime
def parse_datetime(dt_array, cache=None):
if cache is None:
cache = {}
date_time = np.empty(dt_array.shape[0], dtype=object)
for i, (d_str, t_str) in enumerate(dt_array):
try:
year, month, day = cache[d_str]
except KeyError:
year, month, day = [int(item) for item in d_str[:10].split('-')]
cache[d_str] = year, month, day
try:
hour, minute, sec = cache[t_str]
except KeyError:
hour, minute, sec = [int(item) for item in t_str.split(':')]
cache[t_str] = hour, minute, sec
date_time[i] = datetime(year, month, day, hour, minute, sec)
return pd.to_datetime(date_time)
def read_csv(filename, cache=None):
df = pd.read_csv(filename)
df['date_time'] = parse_datetime(df.loc[:, ['date', 'time']].values, cache=cache)
return df.set_index('date_time')
使用以下特定数据集,加速比为 150 倍以上:
$ ls -lh test.csv
-rw-r--r-- 1 blurrcat blurrcat 1.2M Apr 8 12:06 test.csv
$ head -n 4 data/test.csv
user_id,provider,date,time,steps
5480312b6684e015fc2b12bc,fitbit,2014-11-02 00:00:00,17:47:00,25
5480312b6684e015fc2b12bc,fitbit,2014-11-02 00:00:00,17:09:00,4
5480312b6684e015fc2b12bc,fitbit,2014-11-02 00:00:00,19:10:00,67
在 ipython 中:
In [1]: %timeit pd.read_csv('test.csv', parse_dates=[['date', 'time']])
1 loops, best of 3: 10.3 s per loop
In [2]: %timeit read_csv('test.csv', cache={})
1 loops, best of 3: 62.6 ms per loop
要限制内存使用,只需将 dict 缓存替换为 LRU 之类的东西。