Moving Averages In Pandas

Want to learn more? I recommend these Python books: Python for Data Analysis, Python Data Science Handbook, and Introduction to Machine Learning with Python.

Import modules

import pandas as pd

Create a dataframe

data = {'score': [1,1,1,2,2,2,3,3,3]}
df = pd.DataFrame(data)
df
score
0 1
1 1
2 1
3 2
4 2
5 2
6 3
7 3
8 3
# Calculate the moving average. That is, take
# the first two values, average them,
# then drop the first and add the third, etc.
pd.rolling_mean(df, 2)
score
0 NaN
1 1.0
2 1.0
3 1.5
4 2.0
5 2.0
6 2.5
7 3.0
8 3.0