python - 快速替换 pandas.Series of datetime 的 tzinfo

标签 python datetime numpy pandas

我有一个日期时间的 pandas.Series,需要为其中的每个元素替换 tzinfo。

我知道如何使用 apply 和 python 函数来做到这一点,但它非常慢:MacBookPro 上的 1M 元素需要 ~16s

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

它有一个 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

如您所见~快 100 倍

关于python - 快速替换 pandas.Series of datetime 的 tzinfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33479149/

相关文章:

python - Flask-SocketIO 不能在 Apache/WSGI 上工作

python - 一行命令清除 8000 开放端口,杀死后台运行的 django 开发服务器

MySQL 从小时 :minute format 获取日期

Python 导入指令

python - 使用增量运算符时,numpy 数组之和在数据类型方面的不同行为

python - 填充 numpy 数组的元素

python - 将 Pi 相机模块与 OpenCV Python 结合使用

Python os.walk 和符号链接(symbolic link)

c# - 如何检查日期时间段的交集

mysql - SQL - 选择>=和<=的所有行