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

Plu*_*ug4 11 python pandas

我有一个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
Run Code Online (Sandbox Code Playgroud)

如何使用相同的时间戳创建此数据框的列,但舍入到最接近的第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
Run Code Online (Sandbox Code Playgroud)

cro*_*nos 15

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

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))
Run Code Online (Sandbox Code Playgroud)

让我们来比较速度:

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
Run Code Online (Sandbox Code Playgroud)

快了大约1000倍!

  • @Marius Ion:这里不需要小心.一天的长度是无关紧要的.如果DatetimeIndex具有时区,则`astype`操作将转换为UTC.只需将结果转换回您的时区(例如,使用`tz_localize("UTC").tz_convert("US/Eastern")`) (2认同)

Gui*_*ido 13

可以轻松使用pandas的round函数

df["timestamp_column"].dt.round("5min")
Run Code Online (Sandbox Code Playgroud)

查看此处了解更多详情


dus*_*yle 5

你可以尝试这样的事情:

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)
Run Code Online (Sandbox Code Playgroud)