How to calculate inverse cumsum in pandas

后端 未结 2 1229
孤独总比滥情好
孤独总比滥情好 2021-01-28 10:59

I am trying to find a way to calculate an inverse cumsum for pandas. This means applying cumsum but from bottom to top. The problem I\'m facing is, I\'m trying to f

2条回答
  •  花落未央
    2021-01-28 11:19

    Invert the row order of the DataFrame prior to grouping so that the cumsum is calculated in reverse order within each month.

    df['inv_workable_day'] = df[::-1].groupby('month')['flag_workable'].cumsum()
    df['workable_day'] = df.groupby('month')['flag_workable'].cumsum()
    
    #         Date  flag_workable  month  inv_workable_day  workable_day
    #1  2019-01-02           True      1               5.0           1.0
    #2  2019-01-03           True      1               4.0           2.0
    #3  2019-01-04           True      1               3.0           3.0
    #6  2019-01-07           True      1               2.0           4.0
    #7  2019-01-08           True      1               1.0           5.0
    #8  2019-02-01           True      2               1.0           1.0
    

提交回复
热议问题