def lookup(s):
"""
This is an extremely fast approach to datetime parsing.
For large data, the same dates are often repeated. Rather than
re-parse these, we store all unique dates, parse them, and
use a lookup to convert all dates.
"""
dates = {date:pd.to_datetime(date) for date in s.unique()}
return s.map(dates)
像这样使用:
df['date-column'] = lookup(df['date-column'])
基准:
$ python date-parse.py
to_datetime: 5799 ms
dateutil: 5162 ms
strptime: 1651 ms
manual: 242 ms
lookup: 32 ms
Tue Jan 24 12:18:27 2017 - Loading the Temperature data file.
Tue Jan 24 12:18:27 2017 - Temperature file is 88.172 MB.
Tue Jan 24 12:18:27 2017 - Loading into memory. Please be patient.
Tue Jan 24 12:26:35 2017 - Success: loaded 2,169,903 records.
使用infer_datetime_format=True,需要13秒:
Tue Jan 24 13:19:58 2017 - Loading the Temperature data file.
Tue Jan 24 13:19:58 2017 - Temperature file is 88.172 MB.
Tue Jan 24 13:19:58 2017 - Loading into memory. Please be patient.
Tue Jan 24 13:20:11 2017 - Success: loaded 2,169,903 records.
使用缓存优化日期分析
读取所有数据然后转换它总是比读取CSV时转换慢。因为如果您立即执行,就不需要对所有数据重复两次。你也不必把它作为字符串存储在内存中。
我们可以定义自己的日期解析器,它使用缓存来存储已经看到的日期。
与@fixxer的答案具有相同的优点,只解析每个字符串一次,额外的好处是不必读取所有数据然后解析它。节省内存和处理时间。
尝试使用此函数分析日期:
像这样使用:
基准:
来源:https://github.com/sanand0/benchmarks/tree/master/date-parse
伟大的建议@EdChum!正如@EdChum所建议的那样,使用
infer_datetime_format=True
可以显著地加快速度。下面是我的例子。我有一个传感器日志中的温度数据文件,如下所示:
我的代码读取csv并解析日期(
parse_dates=['Date']
)。 使用infer_datetime_format=False
,需要8分钟8秒:使用
infer_datetime_format=True
,需要13秒:相关问题 更多 >
编程相关推荐