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
Write the business question first, and only then choose rank or cumsum. Always sort the data before cumsum, because a running total in the wrong order gives a wrong number. When you show ranks, write the tie rule (average, dense or min) in the caption so that people are not confused.
Ravindra Bagale's Tip – मराठी
आधी business प्रश्न लिहा, आणि त्यानंतरच rank वापरायचा की cumsum ते ठरवा. cumsum आधी data नेहमी sort करा, कारण चुकीच्या order मधला running total चुकीचा आकडा देतो. Ranks दाखवताना tie rule (average, dense किंवा min) caption मध्ये लिहा, म्हणजे लोकांचा गोंधळ होणार नाही.
Ravindra Bagale's Tip – हिंदी
पहले business सवाल लिखो, और उसके बाद ही तय करो कि rank चाहिए या cumsum। cumsum से पहले data हमेशा sort करो, क्योंकि गलत order वाला running total गलत number देता है। Ranks दिखाते समय tie rule (average, dense या min) caption में लिखो, ताकि लोग उलझें नहीं।