← All Python interview questions
Top-selling product in every city
HardPandas — GroupByFlipkartWalmart
Category managers want the single best-selling product per city by revenue — the pandas equivalent of a ROW_NUMBER() window function.
Write a function top_product(df) that returns a dictionary mapping each city to the product with the highest total amount in that city. When two products tie, return the one that comes first alphabetically.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
df = pd.DataFrame(
{
"city": [
"Pune", "Pune", "Pune", "Delhi", "Delhi",
"Delhi", "Mumbai", "Mumbai", "Mumbai",
],
"product": [
"Laptop", "Mouse", "Laptop", "Monitor", "Laptop",
"Monitor", "Mouse", "Monitor", "Mouse",
],
"amount": [40000, 800, 35000, 12000, 55000, 9000, 700, 15000, 1300],
}
)- Step 1: Aggregate first. `groupby(["city", "product"])` with `as_index=False` gives a tidy frame of one row per city-product pair and its total revenue.
- Step 2: Sort by `city` ascending, `amount` descending, then `product` ascending. That third key is what makes ties deterministic instead of dependent on row order.
- Step 3: `drop_duplicates(subset=["city"], keep="first")` keeps the top row of each city block — the pandas idiom for `ROW_NUMBER() OVER (PARTITION BY city ORDER BY amount DESC) = 1`.
- Step 4: `dict(zip(...))` reshapes the two winner columns into the requested mapping.
- Step 5: `idxmax()` looks tempting but silently picks an arbitrary winner on ties, which is why the explicit sort is safer.
import pandas as pd
def top_product(df):
totals = df.groupby(["city", "product"], as_index=False)["amount"].sum()
ranked = totals.sort_values(["city", "amount", "product"], ascending=[True, False, True])
winners = ranked.drop_duplicates(subset=["city"], keep="first")
return dict(zip(winners["city"], winners["product"]))Learn the concept first
Stuck on Pandas — GroupBy? These free Python lessons teach it step by step.
More Pandas — GroupBy questions
Asked at Flipkart
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