Skip to content
Advertisement

Calculate 14-day rolling average on data with two hierarchies

I am trying to calculate the 14 day rolling average for retail data with multiple different hierarchies. The ‘Store’ dataframe looks like this:

JavaScript

What I am trying to do is create a rolling 14 day average for the purchases column for each store. The data extends well past 14 day (over 8 months), and I would like the first 14 days of each store to be a simple average. My issue is that while I can group by ‘Store’ and create a column, I don’t know how to also group by dates. I’ve tried:

JavaScript

and also:

JavaScript

The first one doesn’t seem to have any effect while the second one doesn’t group by dates so I end up with a rolling average in the wrong order. Any advice would be much appreciated!

Edit: The following lines worked, thanks to all for the feedback.

JavaScript

Advertisement

Answer

I believe it’s working fine as long as you sort inplace and remove ‘Date’ from groupby:

JavaScript

Output:

JavaScript
Advertisement