Pandas 包括前几天和未来几天的滚动总和

Pandas rolling sum that includes previous and coming days

初学者,基本上,试图找到包括今天、过去 4 天和未来几天的滚动总和,在本例中为 1 下一天(明天)。

            Test
1995-07-01    1 
1995-07-02    0 
1995-07-03    0 
1995-07-04    1    
1995-07-05    0    
1995-07-06    0    
1995-07-07    0    
1995-07-08    0    
1995-07-09    0    
1995-07-10    0    
1995-07-11    1

得到 'today' 和过去 4 天工作的滚动总和 df['test'].rolling(5).sum()

1995-07-01    NaN
1995-07-02    NaN
1995-07-03    NaN
1995-07-04    NaN
1995-07-05    2.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    1.0
1995-07-09    0.0
1995-07-10    0.0
1995-07-11    1.0

但是将第二天的值包含到这个总和中对我来说很难,我想要的是输出 1995-07-10 显示 1 因为它需要包含 'tomorrow'(自 1995-07-11在测试数据中是 1)

我相信你需要的是shift()方法。它允许您将数据移动几天,然后您可以根据需要将其与日期对齐。

See this link 用于文档。

df['test'].shift(-1,fill_value=0).rolling(5).sum()

提供:

date
1995-07-01    NaN
1995-07-02    NaN
1995-07-03    NaN
1995-07-04    NaN
1995-07-05    1.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    0.0
1995-07-09    0.0
1995-07-10    1.0
1995-07-11    1.0

使用

pd.Series(df.Test.iloc[0]).append(df.Test.shift(-1)) \
                          .rolling(6, min_periods=1).sum().iloc[1:].astype(int)

结果(原来的系列在这里只是为了方便快速检查)

--- Result ---                -- (Original) --

           Test                           Test
1995-07-01    1               1995-07-01     1
1995-07-02    1               1995-07-02     0
1995-07-03    2               1995-07-03     0
1995-07-04    2               1995-07-04     1
1995-07-05    2               1995-07-05     0
1995-07-06    1               1995-07-06     0
1995-07-07    1               1995-07-07     0
1995-07-08    1               1995-07-08     0
1995-07-09    0               1995-07-09     0
1995-07-10    1               1995-07-10     0
1995-07-11    1               1995-07-11     1

解释:

  1. 我们想将 df.Test 系列 1 的位置向上移动以包括第二天 ("tomorrow") 进入滚动 window,但它有一个不好的结果——原始系列的第一个成员消失了。

  2. 所以我们以1元级数(pd.Series(df.Test.iloc[0]))的形式保存(df.Test.iloc[0]).

  3. 然后我们才执行原始系列 (df.Test.shift(-1)) 的预期移位。

  4. 我们将生成的移位序列附加到之前保存的 1 元素序列 (pd.Series(df.Test.iloc[0]).append(df.Test.shift(-1)))。

  5. 现在我们准备创建滚动 window,大小为 6(4 天前 + 今天 + 明天),最小周期为 1 以防止出现 NaN值 (.rolling(6, min_periods=1)).

  6. 最后的步骤现在很明显了:

    • 应用.sum()方法,
    • 删除第一个元素 (.iloc[1:]),它被添加到仅用于滚动 window 计算的移位序列中,
    • 可能会将结果系列的数据类型转换回整数类型(.astype(int))
df['Tomorrow'] = df.shift(-1)
df['Previous'] = df['Test'].rolling(4).sum()
df.sum(axis=1)

Output

1995-07-01    1.0
1995-07-02    0.0
1995-07-03    1.0
1995-07-04    3.0
1995-07-05    1.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    0.0
1995-07-09    0.0
1995-07-10    1.0
1995-07-11    2.0

或者如果您希望前 3 行具有前 4 行的值,即使少于 4 天:

df['Previous'] = df['Test'].rolling(4, min_periods=1).sum()