Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती

25.4 Group-wise rank आणि cumsum

By Ravindra Bagale

या course चे सर्व chapters (py + ch)

हे का शिकायचं?

संपूर्ण देश एका leaderboard पेक्षा city निहाय rank जास्त अर्थपूर्ण.

हे काय आहे?

groupby("city")[col].rank(...) आणि groupby.cumsum().

कसं करायचं?

Step 1. Group key ठरवा.

Step 2. group rank.

Step 3. group cumsum.

Step 4. एक city filter करून verify.

उदाहरणं: copy करा आणि चालवा

उदाहरण 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"]))

उदाहरण 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)

उदाहरण C — Top-1 per city.

top1 = df.loc[df["city_rank"] == 1, ["city", "order_id", "amount_inr"]]
print(top1)