python - 使用 Pandas 中的日期时间索引滚动前瞻总和

标签 python pandas

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

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

对于这个简化的示例,我希望 event_ind 的 future 2 天总和按 id 分组

出于某种原因,改编这个例子仍然给我“索引不是单调错误”: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

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

编辑:

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

最佳答案

您仍然可以在此处使用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

关于python - 使用 Pandas 中的日期时间索引滚动前瞻总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51618554/

相关文章:

python - 从 UTC 偏移获取时区缩写

python - 用 python 中可能的字典列表展平嵌套字典

python - 不使用 Matplotlib Python 在后台获取热图

python - 将两个列表合并为一个多维列表

python - Matplotlib:双 y 轴图未对齐

python - 将一个数据框中的零值列替换为另一个数据框中同名列的平均值

python - 从部分分类列获取 value_counts

匹配模式的 Python 模块

python - 使用条件,在 pandas DataFrame 中选择所需的列

python - 'utf- 8' codec can' t 解码位置 11 中的字节 0x92 : invalid start byte