~/learn/Pandas · Time series

Rolling windows and shifts

Moving averages, period-over-period change and cumulative totals.

9 min readlesson 11 of 13rollingshiftpct_change

why this matters

Moving averages and period-over-period change are the two charts every business dashboard shows.

rolling(n) creates a moving window over the previous n rows. It is how you smooth noisy daily series into a readable trend.

python · editable
loading editor…

Try it: Use min_periods=1 so the first rows are not NaN.

shift moves values along the index, so pct_change and diff give day-over-day change. expanding() accumulates from the start instead of a fixed window.

python · editable
loading editor…

Note

Sort by time before any rolling or shift operation. On unsorted data the results are silently wrong rather than an error.

Three tools

rolling(3).mean()  → average of this row + 2 before
shift(1)           → yesterday's value on today's row
cumsum()           → running total

Common gotcha

The first rows of a rolling window are NaN because there aren't enough prior rows yet. Use min_periods=1 if you want partial values.

key takeaways

  • rolling(n) makes a moving window of n rows.
  • shift moves values up or down rows.
  • Percentage change = (x - x.shift(1)) / x.shift(1).

check your understanding

Why are the first two values of rolling(3).mean() NaN?

free practice

Build confidence with a question you can solve without Pro.