Skip to main content
 首页 » 编程设计

python之在 Pandas 中有效地计算具有回顾期的滚动平均值

2024年12月31日8webabcd

我有一个 Pandas 数据框

                     cumm_vol  cumm_vol_LB 
datetime                                   
2018-01-01 09:15:00     93228            0 
2018-01-01 09:16:00    124353            0 
2018-01-01 09:17:00    184578            0 
2018-01-01 09:18:00    237003            0 
2018-01-01 09:19:00    264303            0 
2018-01-01 09:20:00    310503            0 
2018-01-02 09:15:00    170928            0 
2018-01-02 09:16:00    261528            0 
2018-01-02 09:17:00    358653            0 
2018-01-02 09:18:00    438678            0 
2018-01-02 09:19:00    559503            0 
2018-01-02 09:20:00    626178            0 
2018-01-03 09:15:00    175953            0 
2018-01-03 09:16:00    294078            0 
2018-01-03 09:17:00    395853            0 
2018-01-03 09:18:00    447078            0 
2018-01-03 09:19:00    486903            0 
2018-01-03 09:20:00    523578            0 
2018-01-04 09:15:00     82727            0 
2018-01-04 09:16:00    129077            0 
2018-01-04 09:17:00    162752            0 
2018-01-04 09:18:00    194852            0 
2018-01-04 09:19:00    239027            0 
2018-01-04 09:20:00    291677            0 

我必须在过去 x 天窗口的每 1 分钟间隔计算 cumm_vol 的平均值,并将其添加到当前 cumm_vol_LB 列,并且每天向前滚动例如x=2 时,日期 2018-01-01 和 2018-01-02 的 cumm_vol 在 09:15:00 的平均值将为零,对于 2018-01-03 将为 (93228+170928 )/2 = 132078 所以预期的输出将是一种滚动平均值:

                     cumm_vol  cumm_vol_LB 
datetime                                   
2018-01-01 09:15:00     93228            0 
2018-01-01 09:16:00    124353            0 
2018-01-01 09:17:00    184578            0 
2018-01-01 09:18:00    237003            0 
2018-01-01 09:19:00    264303            0 
2018-01-01 09:20:00    310503            0 
2018-01-02 09:15:00    170928            0 
2018-01-02 09:16:00    261528            0 
2018-01-02 09:17:00    358653            0 
2018-01-02 09:18:00    438678            0 
2018-01-02 09:19:00    559503            0 
2018-01-02 09:20:00    626178            0 
2018-01-03 09:15:00    175953            132078 
2018-01-03 09:16:00    294078            192940.5 
2018-01-03 09:17:00    395853            271615.5 
2018-01-03 09:18:00    447078            337840.5 
2018-01-03 09:19:00    486903            523203 
2018-01-03 09:20:00    523578            468340.5 
.......... 

我目前尝试做的方法是过滤掉回溯期 = 2 的日期的数据,同时根据时间进行 groupby 转换并构建新的数据框。

for dateix,date in enumerate(dates): 
        nifty_datewise = nifty_data.groupby('date').get_group(date) 
        nifty_datatemp = groupbytime(nifty_data, nifty_datewise, dates, dateix) 
        nifty_main = nifty_main.append(nifty_datatemp) 
def groupbytime(nifty_datafrm, nifty_datewise, dates, dateix): 
    if dateix-2>=0: 
        nifty_data = nifty_datafrm.loc[dates[dateix-2]: dates[dateix]] 
        datesNew = nifty_data["date"].dt.date.unique() 
        lookback_df = pd.DataFrame() 
        for datei,date in enumerate(datesNew): 
            nifty_df = nifty_data.groupby('date').get_group(date) 
            lookback_df = lookback_df.append(nifty_df) 
        nifty_datewise["cumm_vol_LB"] = lookback_df.groupby('time')['cumm_vol'].transform('mean') 
        return nifty_datewise 
    else: 
        return nifty_datewise 

这似乎不是最佳解决方案。寻找实现这一目标的最佳实践,可能是 pandas 为此类用例内置了一些东西,.rolling 没有帮助,因为它逐行工作。

谢谢

请您参考如下方法:

在重构我的第一个答案时,我发现 pandas 对时间序列数据的处理非常好。你可以阅读here关于它。此外,使用 groupby 对数据进行分组似乎非常有效,并且不会像我最初认为的那样创建多余的数据副本。

答案 A 与数据集大小的比例比答案 B 更好(线性)。我可以在大约 100 毫秒内计算出 20k 的情况(用 ipython 中的 %timeit 测量) .在下面找到我正在测试的数据的摘录。


答案 A:

此方法按分钟对数据进行分组,然后对这些组应用移动平均过滤器。阅读here关于 Pandas 中的窗口函数。给出了指定时间增量的可用偏移量别名列表 here .

def assign_rolling_average(x, dt): 
    x.cumm_vol_LB = x.cumm_vol.rolling(window=dt).mean() 
    return x 
 
dt='3D' # width of rolling average window: 3 days 
# Group data by the time. 
g = df.groupby(lambda x: x.time())    
# Apply the moving average filter on all groups.  
df = g.apply(assign_rolling_average, dt=dt) 

答案 B(慢得多):

这是我原来的回答。它手动识别要操作的行。它涉及具有全长逻辑索引的多个操作,并且可能受到 data locality problems 的影响。 .它在运行时随问题大小呈二次方缩放。

from datetime import timedelta 
 
# Time delta: fix here the width of the time window 
dt = timedelta(days=3) 
 
# Iterate over the rows 
for idx in df.index: 
    date, time = idx.date(), idx.time() 
    mask = ((df.index.time == time)         # Same time of the day 
            & (df.index.date <= date)       # Not later than today  
            & (df.index.date >= (date-dt))) # Not older than (today - dt) 
    df.loc[idx, 'cumm_vol_LB'] = df.loc[mask, 'cumm_vol'].mean() 

这是我测试的数据框:

import pandas as pd 
df = pd.DataFrame([["2018-01-01 09:15:00",  93228, 0], 
                   ["2018-01-01 09:16:00", 124353, 0], 
                   ["2018-01-01 09:17:00", 184578, 0], 
                   ["2018-01-01 09:18:00", 237003, 0], 
                   ["2018-01-01 09:19:00", 264303, 0], 
                   ["2018-01-01 09:20:00", 310503, 0], 
                   ["2018-01-02 09:15:00", 170928, 0], 
                   ["2018-01-02 09:16:00", 261528, 0], 
                   ["2018-01-02 09:17:00", 358653, 0], 
                   ["2018-01-02 09:18:00", 438678, 0], 
                   ["2018-01-02 09:19:00", 559503, 0], 
                   ["2018-01-02 09:20:00", 626178, 0], 
                   ["2018-01-03 09:15:00", 175953, 0], 
                   ["2018-01-03 09:16:00", 294078, 0], 
                   ["2018-01-03 09:17:00", 395853, 0], 
                   ["2018-01-03 09:18:00", 447078, 0], 
                   ["2018-01-03 09:19:00", 486903, 0], 
                   ["2018-01-03 09:20:00", 523578, 0], 
                   ["2018-01-04 09:15:00",  82727, 0], 
                   ["2018-01-04 09:16:00", 129077, 0], 
                   ["2018-01-04 09:17:00", 162752, 0], 
                   ["2018-01-04 09:18:00", 194852, 0], 
                   ["2018-01-04 09:19:00", 239027, 0], 
                   ["2018-01-04 09:20:00", 291677, 0]], 
                  columns = ['datetime', 'cumm_vol', 'cumm_vol_LB'] 
                  ) 
df = df.set_index('datetime') 
df.index = pd.to_datetime(df.index)