速度差pd.to\ U日期时间两种不同格式

2024-04-29 12:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的数据帧中有两个不同的日期列,我想将其转换为datetime64。你知道吗

一个有格式

0    2009-03-09

转换得相当快:

%timeit pd.to_datetime(df.acquisition_date)
10000 loops, best of 3: 97.9 µs per loop

另一种格式是:

0    2013-01-07 01:02:38 UTC

而且它的转换需要大约18倍的时间:

%timeit pd.to_datetime(df.created_at)
1000 loops, best of 3: 1.74 ms per loop

我能做些什么来加快速度?你知道吗

编辑: 建议的一些结果(df.created_atslow格式):

%timeit pd.to_datetime(df.acquisition_date)
%timeit pd.to_datetime(df.created_at)
%timeit pd.to_datetime(df.created_at, infer_datetime_format=True)
%timeit pd.to_datetime(df.created_at, format='%Y-%m-%d %H:%M:%S %Z')
10000 loops, best of 3: 98.5 µs per loop
1000 loops, best of 3: 1.73 ms per loop
1000 loops, best of 3: 955 µs per loop
1000 loops, best of 3: 222 µs per loop

Tags: oftoloopdfdatetimedate格式at
1条回答
网友
1楼 · 发布于 2024-04-29 12:12:44

尽可能明确。你知道吗

 > dates = pd.Series(['2013-01-07 01:02:38 UTC']*100000)
 > %timeit pd.to_datetime(dates)
 ^C
 > %timeit pd.to_datetime(dates, format='%Y-%m-%d %H:%M:%S %Z')
 1 loops, best of 3: 570 ms per loop

奇怪的是,这似乎伤害了另一种人。你知道吗

> dates = pd.Series(['2009-03-09']*100000)
> %timeit pd.to_datetime(dates)
10 loops, best of 3: 22.2 ms per loop
> %timeit pd.to_datetime(dates, format='%Y-%m-%d')
1 loops, best of 3: 342 ms per loop

请注意,长格式时间戳的首选格式使我们能够加快速度:

> dates = pd.Series(['2013-01-07T01:02:38Z']*100000)
> %timeit pd.to_datetime(dates)
10 loops, best of 3: 23.1 ms per loop

相关问题 更多 >