v Moving Averages In Pandas - Python

Moving Averages In Pandas

Import Modules

# Import pandas
import pandas as pd

Create Dataframe

# Create data
data = {'score': [1,1,1,2,2,2,3,3,3]}

# Create dataframe
df = pd.DataFrame(data)

# View dataframe
df
score
0 1
1 1
2 1
3 2
4 2
5 2
6 3
7 3
8 3

Calculate Rolling Mean

# Calculate the moving average. That is, take
# the first two values, average them, 
# then drop the first and add the third, etc.
df.rolling(window=2).mean()
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