25. How to Rank and Running Totals in pandas (rank, cumsum, window)
25.4 Group-wise Rank and Cumsum
Why. Global rank says Nashik’s best order is #40 statewide. Pune manager wants within Pune ranks. Same for running GMV per city.
What.
df.groupby("city")["amount_inr"].rank(ascending=False, method="dense")df.groupby("city")["gmv"].cumsum()after sorting by city + date
How.
Within-city leaderboard + running GMV
- Sort by
city, thenorder_date(or amount for ranks only). - Add
city_rankwith groupby rank. - Add
city_running_gmvwith groupby cumsum on a GMV column. - Spot-check one city with
.loc[df.city == "Pune"]. - Confirm each city’s running total resets (first Pune row ≠ continue from Nashik).
Worked example A — Rank inside each city.
import pandas as pd
df = pd.DataFrame({
"order_id": ["BLK-1", "BLK-2", "BLK-3", "AMN-4", "BLK-5", "BLK-6"],
"city": ["Pune", "Pune", "Pune", "Nashik", "Nashik", "Kolhapur"],
"amount_inr": [210, 180, 210, 95, 120, 340],
"customer": ["Ruhi", "Amir", "Zoya", "Ravina", "Salman", "Rani"],
})
df["city_rank"] = (
df.groupby("city")["amount_inr"]
.rank(ascending=False, method="dense")
)
print(df.sort_values(["city", "city_rank"]))
Worked example B — Running GMV per city.
daily = pd.DataFrame({
"city": ["Pune", "Pune", "Pune", "Nashik", "Nashik"],
"order_date": pd.to_datetime(
["2026-10-22", "2026-10-23", "2026-10-24", "2026-10-23", "2026-10-24"]
),
"gmv": [50000, 62000, 71000, 22000, 25000],
})
daily = daily.sort_values(["city", "order_date"])
daily["city_running"] = daily.groupby("city")["gmv"].cumsum()
print(daily)
Worked example C — Top-1 per city.
top1 = df.loc[df["city_rank"] == 1, ["city", "order_id", "amount_inr"]]
print(top1)
Ravindra Bagale's Tip
A rank across all stores and a rank inside each city give different answers. Tell your manager first which one you are showing. Then check one group by hand, and if the running total for Pune looks wrong, your groupby key is probably wrong.
Ravindra Bagale's Tip – मराठी
सगळ्या stores मधला rank आणि प्रत्येक city मधला rank वेगवेगळी उत्तरं देतात. तुम्ही कोणता rank दाखवत आहात ते manager ला आधी सांगा. मग एक group हाताने तपासा, आणि Pune चा running total चुकीचा दिसत असेल तर तुमची groupby key बहुतेक चुकीची आहे.
Ravindra Bagale's Tip – हिंदी
सभी stores में rank और हर city के अंदर rank अलग-अलग जवाब देते हैं। आप कौन सा rank दिखा रहे हो, यह manager को पहले बताओ। फिर एक group हाथ से जाँचो, और अगर Pune का running total गलत दिखे तो आपकी groupby key शायद गलत है।