Skip to content
Advertisement

Getting Rolling Sum per Group

I have a dataframe like this:

JavaScript

I would like to get the Sum of the last three months (excluding the current month), per Product_ID.

Therefore I tried this:

JavaScript

My code is failing, because it does not only calculate it per product, but it will give me also numbers for other products (let’s say Product 2, quarter 1: gives me the 3 rows from product 1).

My proposed outcome:

JavaScript

Advertisement

Answer

You need to apply the rolling sum per group, you can use apply for this:

JavaScript

output:

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