我正在读取一个巨大的 CSV
,其中包含格式为 YYYYMMDD
的日期字段,并且我在读取时使用以下 lambda 进行转换:
import pandas as pd
df = pd.read_csv(filen,
index_col=None,
header=None,
parse_dates=[0],
date_parser=lambda t:pd.to_datetime(str(t),
format='%Y%m%d', coerce=True))
虽然这个函数很慢。
有什么改进的建议吗?
最佳答案
注意:如 @ritchie46's answer状态,此解决方案可能是多余的,因为根据新参数 cache_dates
的 pandas 版本为 0.25默认为 True
尝试使用此函数解析日期:
def lookup(date_pd_series, format=None):
"""
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, format=format) for date in date_pd_series.unique()}
return date_pd_series.map(dates)
像这样使用它:
df['date-column'] = lookup(df['date-column'], format='%Y%m%d')
基准测试:
$ python date-parse.py
to_datetime: 5799 ms
dateutil: 5162 ms
strptime: 1651 ms
manual: 242 ms
lookup: 32 ms
来源:https://github.com/sanand0/benchmarks/tree/master/date-parse
关于python - Pandas :缓慢的日期转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29882573/