您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Pandas:时间戳记索引四舍五入到最接近的第5分钟

Pandas:时间戳记索引四舍五入到最接近的第5分钟

round_to_5min(t)使用timedelta算术的解决方案是正确的,但是很复杂而且很慢。而是Timstamp在pandas中使用漂亮的东西:

import numpy as np
import pandas as pd

ns5min=5*60*1000000000   # 5 minutes in nanoseconds 
pd.to_datetime(((df.index.astype(np.int64) // ns5min + 1 ) * ns5min))

让我们比较一下速度:

rng = pd.date_range('1/1/2014', '1/2/2014', freq='S')

print len(rng)
# 86401

# ipython %timeit 
%timeit pd.to_datetime(((rng.astype(np.int64) // ns5min + 1 ) * ns5min))
# 1000 loops, best of 3: 1.01 ms per loop

%timeit rng.map(round_to_5min)
# 1 loops, best of 3: 1.03 s per loop

快大约1000倍!

其他 2022/1/1 18:29:36 有458人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶