I have a pandas df as follows:
YEAR MONTH USERID TRX_COUNT
2020 1 1 1
2020 2 1 2
2020 3 1 1
2020 12 1 1
2021 1 1 3
2021 2 1 3
2021 3 1 4
I want to sum the TRX_COUNT such that, each TRX_COUNT is the sum of TRX_COUNTS of the next 12 months.
So my end result would look like
YEAR MONTH USERID TRX_COUNT TRX_COUNT_SUM
2020 1 1 1 5
2020 2 1 2 7
2020 3 1 1 8
2020 12 1 1 11
2021 1 1 3 10
2021 2 1 3 7
2021 3 1 4 4
For example TRX_COUNT_SUM for 2020/1 is 1+2+1+1=5 the count of the first 12 months.
Two areas I am confused how to proceed:
I tried various variations of
cumsumand grouping byUSERID, YR, MONTHbut am running into errors with handling the time window as there might beMONTHSwhere a user has no transactions and these have to be accounted for. For example in2020/1the user has no transactions for months 4-11, hence a full year of transaction count would be 5.Towards the end there will be partial years, which can be summed up and left as is (like
2021/3which is left as 4).
Any thoughts on how to handle this? Thanks!