How to calculate inverse cumsum in pandas

后端 未结 2 1203
孤独总比滥情好
孤独总比滥情好 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: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   
    

提交回复
热议问题