Window functions compute over a sliding set of rows while keeping every row — moving averages, running totals, period-over-period change. Chapter 7 met rolling on time series; here's the fuller toolkit, including how to keep windows inside groups.
Rolling windows
df["ma7"] = df["sales"].rolling(7).mean() # 7-row moving averagedf["max30"] = df["sales"].rolling(30).max() # rolling maxdf["vol"] = df["sales"].rolling(7, min_periods=1).std() # tolerate short starts
Expanding & EWM
An expanding window grows from the start (cumulative-so-far); EWM weights recent points more heavily than old ones:
df["running_avg"] = df["sales"].expanding().mean() # avg of all rows up to heredf["cumtotal"] = df["sales"].cumsum() # running totaldf["ewm"] = df["sales"].ewm(span=10).mean() # recent-weighted average
shift, diff & pct_change
Compare each row to an earlier one — the basis of growth and lag features:
df["prev"] = df["sales"].shift(1) # value from the previous rowdf["change"] = df["sales"].diff() # this − previousdf["growth"] = df["sales"].pct_change() # fractional changedf["rank"] = df["sales"].rank(ascending=False) # rank within the column
Windows within groups
# 7-day average per store, not bleeding across storesdf["store_ma7"] = df.groupby("store")["sales"].transform(lambda s: s.rolling(7).mean())df["store_prev"] = df.groupby("store")["sales"].shift(1)
Practice
On a daily sales series, add a 7-day moving average, a running total, and an EWM. Add previous-value, absolute-change and percentage-change columns with shift/diff/pct_change. Then redo the moving average per category with a grouped window and confirm it no longer bleeds across categories.
Key takeaways
- 01rolling(n) computes a fixed-size sliding statistic; min_periods tolerates short starts.
- 02expanding grows from the start (cumulative); ewm weights recent points more heavily.
- 03shift accesses earlier rows; diff and pct_change measure absolute and fractional change.
- 04rank orders values within a column.
- 05groupby before rolling/shift to keep windows inside each group — plain versions bleed across categories.
