Window functions compute over a sliding range of rows — moving averages to smooth noise, cumulative totals, and comparisons to previous periods. They're essential for trends and time-series features.
Rolling windows
ts["ma7"] = ts["sales"].rolling(7).mean() # 7-day moving averagets["max30"] = ts["sales"].rolling(30).max() # 30-day rolling maxts["cumsum"] = ts["sales"].cumsum() # running total
shift, diff & pct_change
ts["prev"] = ts["sales"].shift(1) # yesterday's valuets["change"] = ts["sales"].diff() # absolute change vs previousts["growth"] = ts["sales"].pct_change() # percent change
Key takeaways
- 01rolling(n) computes over a sliding window — moving average, rolling max, etc.
- 02cumsum/cumprod give running totals.
- 03shift moves values by n rows; diff and pct_change compare to the previous period.
- 04The first window-1 rolling values are NaN by design.
