【问题标题】:Pandas groupby to compute rolling sum over the next n-daysPandas groupby 计算未来 n 天的滚动总和
【发布时间】:2021-03-11 16:48:29
【问题描述】:

我有以下数据框:

 print(df)
    
   dt_op_f      ID_FAR     cod_id   quantity    sales_next_days
  2019-01-12      10       1234        10        30 = 10+15+5    

  2019-01-13      10       1234        15        20 = 15+5       
  2019-01-13      3        1234         5        10 = 5+5

  2019-01-14      10        112         5         5
  2019-01-14      3        1234         5         5

  2019-01-15      10       1234         5         5

对于企业 ID(“ID_FAR”)和产品 ID(“cod_id”)的每个组合,我想计算接下来 n 天的销售额(“数量”)总和(n 等于 7 );

我试过了:

df.set_index('dt_op_f').groupby(['cod_id', "ID_FAR"]).rolling('7d', min_periods=1).quantity.sum()

但它只适用于“过去”的 n 天。

我怎样才能做到这一点?

【问题讨论】:

标签: python-3.x pandas


【解决方案1】:

我认为您可以按降序翻转索引并在之后应用滚动:

df.set_index('dt_op_f').sort_index(ascending = False).groupby(['cod_id', "ID_FAR"]).rolling('7d', min_periods=1).quantity.sum().sort_index()

生产

cod_id  ID_FAR  dt_op_f   
112     10      2019-01-14     5.0
1234    3       2019-01-13    10.0
                2019-01-14     5.0
        10      2019-01-12    30.0
                2019-01-13    20.0
                2019-01-15     5.0
Name: quantity, dtype: float64

【讨论】:

    猜你喜欢
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2014-05-04
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多