Ravindra BagaleCourses & study guides मराठी Track your progress

25. How to Rank and Running Totals in pandas (rank, cumsum, window)

Data Science

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

  1. Sort by city, then order_date (or amount for ranks only).
  2. Add city_rank with groupby rank.
  3. Add city_running_gmv with groupby cumsum on a GMV column.
  4. Spot-check one city with .loc[df.city == "Pune"].
  5. 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.