Skip to content
Advertisement

How to calculate 12 month rolling sum based on groupby?

I am trying to calculate the 12 month rolling sum for the number of orders and revenue based on a person’s name using Python for the following dataframe:

JavaScript

In order to give the following output:

JavaScript

The rolling sum should add up all the totals in the past 12 months grouped by the name column.

I have tried the following:

JavaScript

but it does not give me the expected result.

Advertisement

Answer

You’re passing the rolling frequency as 12, pandas does not know that you want to specify a 12 months window, also you need to make sure that your Month column is identified as a date type column, try this:

JavaScript

Also, you need to use 365d instead of 12m, since using 12m would throw an error : ValueError: <12 * MonthEnds> is a non-fixed frequency.

A brief explanation for this is that a rolling window must have a fixed width – “a month” does not have a fixed number of days.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement