rolling
What it is
A sliding window: rolling(7).mean() over seven rows, or rolling("7D").sum() over seven days on a time index. min_periods decides how partial windows are treated.
Why it matters
Recent-behaviour features — spend in the last seven days, error rate in the last hour — are the most predictive features in most applied problems.
In the real world: A 7-day average of daily sales smooths out the weekend spikes so a manager can see whether the business is really growing.
Visual example
WindowsA rolling window keeps its width and slides: each output sees itself and the rows just before it.
The first few sums
3 + 1 + 4 = 8
1 + 4 + 1 = 6
4 + 1 + 5 = 10
Why this matters
Recent behaviour — spend in the last 7 days, errors in the last hour — is among the most predictive features there is, and it never reads the future.
Common misconception
Wrong idea: the first rows get a partial sum.
Correct idea: they get NaN until the window is full. min_periods changes that.
- 1Cover 3 rowsThe window ends at the current row.
- 2AggregateSum what is inside it.
- 3Slide oneDrop the oldest row, take the next.
ts = df.set_index("ts").sort_index()
ts["spend_7d"] = ts["total"].rolling("7D").sum() # seven days
ts["avg_7"] = ts["total"].rolling(7, min_periods=3).mean() # seven rowsA row-count window on irregular data is not seven days, it is seven observations. Use the time-based form when the interval is what matters.
Practise it: Rolling 7-Day Spend Per Customer