时区感知 Pandas DateTimeIndex 的性能

Performance of timezone-aware Pandas DateTimeIndex

我在网上搜索,但没有找到任何关于我面临的问题的信息。

似乎 pandas.DataFrame 对具有时区感知日期的索引的操作比对常规日期时间慢一个数量级。

这是 ipython 时间安排。

首先使用标准日期时间:

import pandas as pd
import numpy as np

dates=pd.date_range('2010/01/01 00:00:00', '2010/12/31 00:00:00', freq='1T')
DF=pd.DataFrame(data=np.random.rand(len(dates)), index=dates, columns=["value"])

# compute timedeltas between dates
%timeit DF["temp"] = DF.index
%timeit DF["deltas"] = (DF["temp"] - DF["temp"].shift())

结果是:

1000 loops, best of 3: 1.13 ms per loop
100 loops, best of 3: 17.1 ms per loop

到目前为止,还不错。

现在只需添加时区信息:

import pandas as pd
import numpy as np

dates=pd.date_range('2010/01/01 00:00:00', '2010/12/31 00:00:00', freq='1T')
# NEW: filter dates to avoid DST problems
dates=dates[dates.hour>2] # to avoid AmbiguousInferError or NonExistentDateError

DF=pd.DataFrame(data=np.random.rand(len(dates)), index=dates, columns=["value"])

# NEW: add timezone info
DF.index = DF.index.tz_localize(tz="America/New_York", ambiguous="infer")

# compute timedeltas between dates
%timeit DF["temp"] = DF.index
%timeit DF["deltas"] = (DF["temp"] - DF["temp"].shift())

现在,结果是:

1 loops, best of 3: 5.43 s per loop
1 loops, best of 3: 16 s per loop

为什么?
我真的不明白这里的瓶颈在哪里...

获取信息(来自 conda list):

anaconda                  2.2.0                np19py34_0  
conda                     3.12.0                   py34_0  

numpy                     1.9.2                    py34_0  
pandas                    0.16.1               np19py34_0  
pytz                      2015.4                   py34_0  
scipy                     0.15.1               np19py34_0  

这是一个已知问题,请参阅 here。 具有天真的 tz(例如,无时区)Series 的日期时间可以有效地用 datetime64[ns] 的 dtype 表示。使用 int64 等的计算非常快。 tz-aware Series 使用 object dtype 表示。这些计算速度相当慢。

可以解决此问题(请参阅参考问题),以获得统一的 tz 感知 Series。欢迎提出请求!

In [9]: df = DataFrame({'datetime' : pd.date_range('20130101',periods=5), 'datetime_with_tz' : pd.date_range('20130101',periods=5,tz='US/Eastern')})

In [10]: df 
Out[10]: 
    datetime           datetime_with_tz
0 2013-01-01  2013-01-01 00:00:00-05:00
1 2013-01-02  2013-01-02 00:00:00-05:00
2 2013-01-03  2013-01-03 00:00:00-05:00
3 2013-01-04  2013-01-04 00:00:00-05:00
4 2013-01-05  2013-01-05 00:00:00-05:00

In [11]: df.dtypes
Out[11]: 
datetime            datetime64[ns]
datetime_with_tz            object
dtype: object