繁体   English   中英

熊猫:时间戳索引四舍五入到最近的第5分钟

[英]Pandas: Timestamp index rounding to the nearest 5th minute

我有一个通常的时间戳作为索引的df

    2011-04-01 09:30:00
    2011-04-01 09:30:10
    ...
    2011-04-01 09:36:20
    ...
    2011-04-01 09:37:30

如何使用相同的时间戳创建此数据框的列,但舍入到最接近的第5分钟间隔? 像这样:

    index                 new_col
    2011-04-01 09:30:00   2011-04-01 09:35:00        
    2011-04-01 09:30:10   2011-04-01 09:35:00
    2011-04-01 09:36:20   2011-04-01 09:40:00
    2011-04-01 09:37:30   2011-04-01 09:40:00

使用timedelta算法的round_to_5min(t)解决方案是正确的但是复杂且非常慢。 而是在熊猫中使用好的Timstamp

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倍!

你可以尝试这样的事情:

def round_to_5min(t):
    delta = datetime.timedelta(minutes=t.minute%5, 
                               seconds=t.second, 
                               microseconds=t.microsecond)
    t -= delta
    if delta > datetime.timedelta(0):
        t += datetime.timedelta(minutes=5)
    return t

df['new_col'] = df.index.map(round_to_5min)

我有同样的问题,但有datetime64p [ns]时间戳。

我用了:

def round_to_5min(t):
    """ This function rounds a timedelta timestamp to the nearest 5-min mark"""
    t = datetime.datetime(t.year, t.month, t.day, t.hour, t.minute - t.minute%5, 0)  
    return t

然后是'map'功能

人们可以很容易地使用熊猫的圆形功能

df["timestamp_column"].dt.round("5min")

点击此处了解更多详情

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM