25. How to Rank and Running Totals in pandas (rank, cumsum, window)
25.5 Light Windows: rolling and expanding
Why. “Last 3 days average orders” smooths one crazy Diwali spike so Solapur is not punished for one quiet Monday.
What.
rolling(n)— window of the last n rows (after sort).expanding()— from the start through the current row (growing window).- Use
.mean(),.sum(),.median()on the window.
How.
3-day rolling mean
- Day-level series sorted by date.
df["orders_roll3"] = df["orders"].rolling(3).mean().- Expect first two rows as NaN if window needs 3 points (default).
- Optional:
min_periods=1if you want early days filled. - Compare rolling mean vs raw spike before you call a city “down”.
Worked example A — Rolling vs expanding.
import pandas as pd
s = pd.DataFrame({
"order_date": pd.to_datetime(
["2026-10-20", "2026-10-21", "2026-10-22", "2026-10-23", "2026-10-24"]
),
"orders": [400, 420, 410, 900, 880], # Thu spike
})
s = s.sort_values("order_date")
s["roll3"] = s["orders"].rolling(3).mean()
s["expand_mean"] = s["orders"].expanding().mean()
print(s)
Worked example B — Rolling inside each city.
d = pd.DataFrame({
"city": ["Pune"] * 4 + ["Nashik"] * 4,
"day": list(range(1, 5)) * 2,
"orders": [100, 110, 105, 200, 40, 42, 41, 90],
})
d["roll3"] = d.groupby("city")["orders"].transform(
lambda x: x.rolling(3).mean()
)
print(d)
Worked example C — When not to use rolling.
Rani has only two days of Kolhapur data. A rolling(7) is empty almost everywhere — use expanding or wait for more days.
Ravindra Bagale's Tip
A rolling window is like a rear-view mirror that shows only the last N days, while expanding shows the whole season so far. A rolling mean calms down a single spike, so you can see the real trend. Always write the window size in the chart title, such as “7-day rolling mean”, so that readers do not have to guess.
Ravindra Bagale's Tip – मराठी
Rolling window हा फक्त शेवटचे N दिवस दाखवणाऱ्या rear-view mirror सारखा असतो, तर expanding सुरुवातीपासून आतापर्यंतचा पूर्ण season दाखवतो. Rolling mean एकाच spike ला शांत करतो, त्यामुळे खरा trend दिसतो. Chart title मध्ये window size नेहमी लिहा, जसं “7-day rolling mean”, म्हणजे वाचणाऱ्यांना अंदाज लावावा लागणार नाही.
Ravindra Bagale's Tip – हिंदी
Rolling window सिर्फ़ आख़िरी N दिन दिखाने वाले rear-view mirror जैसा है, जबकि expanding शुरुआत से अब तक का पूरा season दिखाता है। Rolling mean एक अकेले spike को शांत कर देता है, जिससे असली trend दिखता है। Chart title में window size हमेशा लिखो, जैसे “7-day rolling mean”, ताकि पढ़ने वालों को अंदाज़ा न लगाना पड़े।