← All Python interview questions
Show each category as a percent of its city revenue
MediumPandas — GroupByNykaaTata CLiQ
The city dashboard shows revenue mix, not absolute revenue.
Write share(df) that returns a DataFrame with city, category and pct — each category's share of that city's total revenue as a percentage rounded to 1 decimal — sorted by city then descending share.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
import numpy as np
orders = pd.DataFrame({
"order_id": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"city": ["Mumbai", "Delhi", "Mumbai", "Bengaluru", "Delhi", "Mumbai", "Bengaluru", "Delhi", "Mumbai", "Bengaluru"],
"category": ["Grocery", "Fashion", "Fashion", "Grocery", "Grocery", "Grocery", "Fashion", "Fashion", "Fashion", "Grocery"],
"amount": [1200.0, 2500.0, 800.0, 1500.0, 640.0, 2200.0, 3100.0, 450.0, 1750.0, 990.0],
"order_date": pd.to_datetime([
"2026-01-05", "2026-01-18", "2026-02-02", "2026-02-14", "2026-02-27",
"2026-03-03", "2026-03-11", "2026-03-19", "2026-04-04", "2026-04-22",
]),
})- Step 1: Aggregate to one row per city/category first — the numerator of the share.
- Step 2: `groupby('city')['amount'].transform('sum')` broadcasts each city's total back onto every one of its rows, which is what makes the division a single vectorised step.
- Step 3: Multiply by 100 and round once, at the end, so the percentages still add up to 100 per city.
- Step 4: Sorting by city then descending share puts the dominant category first, the way the dashboard reads.
def share(df):
totals = df.groupby(["city", "category"], as_index=False)["amount"].sum()
city_total = totals.groupby("city")["amount"].transform("sum")
totals["pct"] = (totals["amount"] / city_total * 100).round(1)
out = totals.sort_values(["city", "pct"], ascending=[True, False])
return out[["city", "category", "pct"]].reset_index(drop=True)Learn the concept first
Stuck on Pandas — GroupBy? These free Python lessons teach it step by step.
More Pandas — GroupBy questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program