Skip to content
Advertisement

Create rolling average pandas

I have a dataset of esports data like this:

(done using pd.to_clipboard()

JavaScript

I want to create a dataframe that essentially, for each team, every week, creates a rolling X game average of their points scored. (X could be 2, 3, 4, etc). A few notes:

  • This example only shows points, the actual data has about 10 features that need rolling averages
  • Ideally, it would be a function, so I could swap X for any given number
  • Not every team plays every week!

I tried to create this functionality using below code:

JavaScript

However, it yields results like:

JavaScript

While I would like for it to look like:

JavaScript

What am I doing wrong? How can I achieve my desired result?

Advertisement

Answer

JavaScript
  • grouping by team
  • selecting columns to be averaged (here Team Points, not using Vs Points since every game appears twice, but you could add your other features to the list)
  • use df.rolling() with a window of 2. The number only appears once so easy to change or use as parameter in a function.

As underlined in another answer this could use the slightly denser notation groupby().rolling(), thus in this case:

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