25. How to Rank and Running Totals in pandas (rank, cumsum, window)
25.6 Common Mistakes
Why. Silent wrong ranks and cumsums look “professional” in Excel exports until someone audits Thursday.
What. Watch for: unsorted dates; ranking the wrong direction; forgetting groupby; applying rolling on ticket-level rows instead of daily aggregates; chaining filters then ranking a copy you throw away.
How.
Checklist before you send
sort_valueson the time key beforecumsum/rolling.- Print
ascending=TruevsFalseintent (speed vs GMV). - For per-city metrics, confirm groupby key spelling (
Punevspune). - Aggregate to day grain before multi-day rolling.
- After rank,
value_countson the rank column to see ties. - Keep a raw column; add rank/cumsum as new columns.
Worked example A — Broken cumsum (forgot sort).
import pandas as pd
messy = pd.DataFrame({
"order_date": pd.to_datetime(["2026-10-24", "2026-10-22", "2026-10-23"]),
"gmv": [140000, 88000, 125000],
})
print("wrong", messy["gmv"].cumsum().tolist())
fixed = messy.sort_values("order_date")
print("right", fixed["gmv"].cumsum().tolist())
Worked example B — Rank direction bug.
mins = pd.Series([18, 11, 25], name="delivery_mins")
# Wrong for "fastest": ranking high minutes first
print("wrong", mins.rank(ascending=False, method="dense").tolist())
print("right", mins.rank(ascending=True, method="dense").tolist())
Worked example C — Rolling on orders grain.
Zoya rolled amount_inr on 5,000 order rows with rolling(3) — that is “last 3 tickets”, not “last 3 days”. Aggregate by date first.
Ravindra Bagale's Tip
Bug checklist: sort, direction, group key, grain. Char shabdat audit.