Rolling Windows

Smoothing a noisy series to see the shape underneath.

A moving average

rolling takes a window and a summary. A seven-day mean of daily numbers removes the weekday pattern and leaves the trend.

import pandas as pd

s = pd.Series([1, 2, 3, 4])
print(s.rolling(2).mean().tolist())

The first values have no window

A window of three has nothing to average until the third value, so the first entries come back missing. That is honest rather than awkward.

import pandas as pd

s = pd.Series([1, 2, 3])
print(s.rolling(3).mean().isna().sum())

Exercise

Try It Yourself

Write smoothed(s, window) returning the rolling mean as a list, with the leading gaps dropped.

Press Run to see output

Check Your Understanding