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
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
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.
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