25. How to Rank and Running Totals in pandas (rank, cumsum, window)
25.2 rank: Place Among Peers
Why. Two Pune orders both ₹210. Is that rank 1 and 1, or 1 and 2? Interviewers love this. Managers hate silent ties.
What. Series.rank(ascending=False, method=...)
| method | Tie behaviour (high amounts first) |
|---|---|
average (default) |
Both get 1.5 if they share #1 |
min |
Both get 1; next gets 3 |
dense |
Both get 1; next gets 2 (no gap) |
first |
Order of appearance breaks the tie |
How.
Rank a money column
- Keep the full DataFrame (do not drop ties yet).
df["rank_amt"] = df["amount_inr"].rank(ascending=False, method="dense").- Sort by rank to show the leaderboard.
- Say the method out loud: dense / min / average.
- For “top N unique places”, filter
rank_amt <= N.
Worked example A — Dense rank on baskets.
import pandas as pd
df = pd.DataFrame({
"order_id": ["BLK-1", "BLK-2", "BLK-3", "AMN-4", "BLK-5"],
"city": ["Pune", "Pune", "Nashik", "Kolhapur", "Pune"],
"amount_inr": [210, 210, 95, 180, 150],
"customer": ["Ruhi Bagale", "Amir", "Zoya", "Ravina", "Salman"],
})
df["rank_dense"] = df["amount_inr"].rank(ascending=False, method="dense")
df["rank_min"] = df["amount_inr"].rank(ascending=False, method="min")
df["rank_avg"] = df["amount_inr"].rank(ascending=False, method="average")
print(df.sort_values("rank_dense")[
["order_id", "amount_inr", "rank_dense", "rank_min", "rank_avg"]
])
What you should see. Both ₹210 rows share dense rank 1; next amount gets 2. min leaves a gap (next is 3). average shows 1.5.
Worked example B — Rank low delivery minutes (faster is better).
df = pd.DataFrame({
"order_id": ["BLK-10", "BLK-11", "AMN-12"],
"city": ["Solapur", "Nagpur", "Pune"],
"delivery_mins": [11, 18, 11],
})
df["fast_rank"] = df["delivery_mins"].rank(ascending=True, method="dense")
print(df.sort_values("fast_rank"))
Worked example C — Interview one-liner.
“I use rank(ascending=False, method='dense') on GMV so ties share a place and the next city is still #2.”
Ravindra Bagale's Tip
Dense rank gives a leaderboard with no gaps, while the average method suits statistics work. For a team update on WhatsApp, dense rank is usually the easiest to read. When the highest number is the best, use ascending=False, and check the order twice before you publish the leaderboard.
Ravindra Bagale's Tip – मराठी
Dense rank मध्ये leaderboard ला मध्ये gaps राहत नाहीत, तर average method statistics च्या कामासाठी योग्य असते. Team ला WhatsApp वर update पाठवताना dense rank वाचायला सर्वात सोपा असतो. सर्वात मोठा आकडा सर्वोत्तम असेल तेव्हा ascending=False वापरा, आणि leaderboard publish करण्याआधी order दोनदा तपासा.
Ravindra Bagale's Tip – हिंदी
Dense rank में leaderboard के बीच में gaps नहीं रहते, जबकि average method statistics के काम के लिए ठीक है। Team को WhatsApp पर update भेजते समय dense rank पढ़ने में सबसे आसान होता है। जब सबसे बड़ा number सबसे अच्छा हो तब ascending=False इस्तेमाल करो, और leaderboard publish करने से पहले order दो बार जाँचो।