How to calculate inverse cumsum in pandas

后端 未结 2 1204
孤独总比滥情好
孤独总比滥情好 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
    
    0 讨论(0)
  • 2021-01-28 11:32

    Solution

    Whichever column you want to apply cumsum to you have two options:
    1. Order descending a copy of that column by index, followed by cumsum and then order ascending by index. Finally assign it back to the data frame column.

    1. Use numpy:
    import numpy as np
    
    array = df.column_data.to_numpy()    
    array = np.flip(array)  # to flip the order 
    array = numpy.cumsum(array)    
    array =  numpy.flip(array)  # to flip back to original order    
    df.column_data_cumsum = array   
    
    0 讨论(0)
提交回复
热议问题