25. How to Rank and Running Totals in pandas (rank, cumsum, window)
25.1 Why Rank and Running Totals
Why. Shraddha Bagale (Pune ops) sorts amount_inr descending and pastes the sheet on WhatsApp. Amir asks: “Is BLK-10 still #1 after ties?” Ruhi asks: “What was cumulative delivered GMV by 6 pm IST?” Sort alone does not answer rank ties or running totals.
What.
- Rank — place of a row among peers (1 = best if you rank high amounts first).
- Running total (
cumsum) — add values in order so each row shows “so far”. - Window — a moving or growing slice (last 3 days, or everything from day 1 until now).
How.
Pick the question first
- Write the manager question in one line.
- If it needs “#1 / #2 / tied” →
rank. - If it needs “GMV so far today” → sort by time, then
cumsum. - If it needs “last 3 days average” →
rolling. - Always check sort order before cumsum or rolling.
Worked example A — Sort vs rank.
import pandas as pd
df = pd.DataFrame({
"order_id": ["BLK-1", "BLK-2", "BLK-3", "AMN-4"],
"city": ["Pune", "Pune", "Nashik", "Pune"],
"amount_inr": [210, 210, 95, 180],
"customer": ["Ruhi Bagale", "Amir", "Zoya", "Ravina"],
})
print(df.sort_values("amount_inr", ascending=False))
Sorting shows order. Ranking labels ties clearly (next section).
Worked example B — Running total need (fictional evening).
Raja in Nagpur sends hourly delivered GMV. The city manager wants one column: cumulative GMV from midnight IST — that is cumsum, not a new groupby.
Worked example C — Decision card.
| Question | Tool |
|---|---|
| Top basket in Pune today | rank (within city) |
| GMV so far this week | cumsum after date sort |
| 3-day moving average orders | rolling(3).mean() |
Ravindra Bagale's Tip
Pehle question. Mag rank ki cumsum. Sort bhulayla naka — cumsum ulat order var galicha number deto.