【问题标题】:Rolling Look Forward Sum with Datetime Index in PandasPandas 中带有日期时间索引的滚动前瞻和
【发布时间】:2019-01-08 03:43:53
【问题描述】:

我有以下简化格式的多元时间序列/面板数据:

id,date,event_ind
1,2014-01-01,0
1,2014-01-02,1
1,2014-01-03,1
2,2014-01-01,1
2,2014-01-02,1
2,2014-01-03,1
3,2014-01-01,0
3,2014-01-02,0
3,2014-01-03,1

对于这个简化的例子,我想要按 id 分组的 event_ind 的未来 2 天总和

由于某种原因,调整此示例仍然给我“索引不是单调错误”:how to do forward rolling sum in pandas?

这是我的方法,在我调整之前,它适用于过去的分组滚动:

df.sort_values(['id','date'], ascending=[True,True], inplace=True)
df.reset_index(drop=True, inplace=True)

df['date'] = pd.DatetimeIndex(df['date'])
df.set_index(['date'], drop=True, inplace=True)

rolling_forward_2_day = lambda x: x.iloc[::-1].rolling('2D').sum().shift(1).iloc[::-1]
df['future_2_day_total'] = df.groupby(['id'], sort=False)['event_ind'].transform(rolling_forward_2_day)
df.reset_index(drop=False, inplace=True)

这是预期的结果:

   id        date  event_ind  future_2_day_total
0   1  2014-01-01          0                   2
1   1  2014-01-02          1                   1
2   1  2014-01-03          1                   0
3   2  2014-01-01          1                   2
4   2  2014-01-02          1                   1
5   2  2014-01-03          1                   0
6   3  2014-01-01          0                   1
7   3  2014-01-02          0                   1
8   3  2014-01-03          1                   0

任何关于我可能做错了什么或高性能替代方案的提示都会很棒!

编辑:

快速澄清一下。此示例经过简化,有效的解决方案需要能够处理间隔不均匀/不规则的时间序列,这就是使用基于时间的索引滚动的原因。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您仍然可以在此处使用 rolling,但将其与标志 win_type='boxcar' 一起使用并在求和前后移动数据:

    df['future_day_2_total'] = (
        df.groupby('id').event_ind.shift(-1)
        .fillna(0).groupby(df.id).rolling(2, win_type='boxcar')
        .sum().shift(-1).fillna(0)
    )
    
       id        date  event_ind  future_day_2_total
    0   1  2014-01-01          0                 2.0
    1   1  2014-01-02          1                 1.0
    2   1  2014-01-03          1                 0.0
    3   2  2014-01-01          1                 2.0
    4   2  2014-01-02          1                 1.0
    5   2  2014-01-03          1                 0.0
    6   3  2014-01-01          0                 1.0
    7   3  2014-01-02          0                 1.0
    8   3  2014-01-03          1                 0.0
    

    【讨论】:

    • "boxcar" 非常棒。您是否有一个很好的资源可以准确解释什么是 boxcar win-type 以及其他 win_types 是什么? +1
    • 感谢您的贡献!不幸的是,这种巧妙地使用 shift() 仅适用于这个简化的示例,但不适用于我的实际任务。在我的实际任务中,我在未来 365 天滚动。
    • @Pylander 我必须对其进行测试,但这应该仍然有效,您只需要更改最后的移动量即可。
    • @ScottBoston 我只知道 boxcar 是在我与 SciPy 一起使用时才知道的。严重缺乏有关不同窗口类型的 pandas 文档。如果我有时间将一些示例放在一起,我可能会考虑向文档提交拉取请求。
    • @user3483203 我认为问题在于,在我的实际情况下,这些实际上不是干净和完整的时间序列,所以我不能使用 shift 并且需要使用 datetime 索引。
    猜你喜欢
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    相关资源
    最近更新 更多