typestar

Rolling windows in Python

A moving average smooths a noisy series without losing its shape.

import pandas as pd

runs = pd.Series([88, 91, 104, 97, 99, 108])

print(runs.rolling(3).mean().round(1).tolist())
print(runs.rolling(3, min_periods=1).mean().round(1).tolist())
print(runs.expanding().max().tolist())
print(runs.diff().tolist())

How it works

  1. rolling(3) looks back three rows, so the first two are missing.
  2. min_periods lets short windows produce a value anyway.
  3. expanding grows the window from the start instead.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
244
Tokens
100
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 3 of 3 in Time series, step 25 of 26 in pandas.

← Previous Next →