Gui*_*mas 5 python datetime numpy pandas
我有一个pandas.Series日期时间,需要替换其中每个元素的 tzinfo 。
我知道如何使用applypython 函数来做到这一点,但它非常慢:MacBookPro 上 1M 元素大约需要 16 秒
In [71]: s = pd.date_range('2015-1-1', freq='h', periods=1e6).to_series().reset_index(drop=True)
In [72]: %timeit s.apply(lambda x: x.replace(tzinfo=pytz.utc))
1 loops, best of 3: 16.7 s per loop
Run Code Online (Sandbox Code Playgroud)
有 numpy ufunc 函数吗?
使用dt.localize:
In [33]:
import pytz
%timeit s.dt.tz_localize(pytz.utc)
%timeit s.apply(lambda x: x.replace(tzinfo=pytz.utc))
10 loops, best of 3: 107 ms per loop
1 loops, best of 3: 10.4 s per loop
Run Code Online (Sandbox Code Playgroud)
如您所见,速度提高约 100 倍