Title: Moving Averages In Pandas
Slug: pandas_moving_average
Summary: Moving Averages In Pandas
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon

Import Modules


In [1]:
# Import pandas
import pandas as pd

Create Dataframe


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

# Create dataframe
df = pd.DataFrame(data)

# View dataframe
df


Out[2]:
score
0 1
1 1
2 1
3 2
4 2
5 2
6 3
7 3
8 3

Calculate Rolling Mean


In [3]:
# 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()


Out[3]:
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