Skip to main content
Albero Academy

Window Functions

Compute rolling, expanding and exponentially-weighted statistics, and compare rows to their neighbours with shift, diff and ranking.

Chapter 11Pandas15 min readBeginner friendly
  • #Pandas
  • #Window
  • #Rolling

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

fixed-size sliding window
df["ma7"] = df["sales"].rolling(7).mean() # 7-row moving average
df["max30"] = df["sales"].rolling(30).max() # rolling max
df["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:

cumulative & weighted
df["running_avg"] = df["sales"].expanding().mean() # avg of all rows up to here
df["cumtotal"] = df["sales"].cumsum() # running total
df["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:

looking backward
df["prev"] = df["sales"].shift(1) # value from the previous row
df["change"] = df["sales"].diff() # this − previous
df["growth"] = df["sales"].pct_change() # fractional change
df["rank"] = df["sales"].rank(ascending=False) # rank within the column

Windows within groups

per-group windows
# 7-day average per store, not bleeding across stores
df["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

  1. 01rolling(n) computes a fixed-size sliding statistic; min_periods tolerates short starts.
  2. 02expanding grows from the start (cumulative); ewm weights recent points more heavily.
  3. 03shift accesses earlier rows; diff and pct_change measure absolute and fractional change.
  4. 04rank orders values within a column.
  5. 05groupby before rolling/shift to keep windows inside each group — plain versions bleed across categories.