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
rolling(3)looks back three rows, so the first two are missing.min_periodslets short windows produce a value anyway.expandinggrows the window from the start instead.
Keywords and builtins used here
asprint
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.
Step 3 of 3 in Time series, step 25 of 26 in pandas.