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
Before you share a result, check four things: the sort order, the direction (ascending or descending), the group key and the grain of each row. A smooth line built on the wrong sort order still looks confident, but it is still wrong. These four checks catch most rank and cumsum bugs.
Ravindra Bagale's Tip – मराठी
निकाल share करण्याआधी चार गोष्टी तपासा: sort order, direction (ascending की descending), group key आणि प्रत्येक row चा grain. चुकीच्या sort order वर बनलेली smooth line सुद्धा खात्रीशीर दिसते, पण ती चुकीचीच असते. या चार checks मुळे rank आणि cumsum चे बहुतेक bugs पकडले जातात.
Ravindra Bagale's Tip – हिंदी
Result share करने से पहले चार चीज़ें जाँचो: sort order, direction (ascending या descending), group key और हर row का grain। गलत sort order पर बनी smooth line भी भरोसेमंद दिखती है, लेकिन वह फिर भी गलत होती है। इन चार checks से rank और cumsum के ज़्यादातर bugs पकड़ में आ जाते हैं।