← All Python interview questions
Compute profit margin per category with groupby
MediumPandas — GroupByDeloitteAccenture
Finance wants a margin per category: total profit divided by total revenue, not the average of the row-level margins.
Write margins(df) that returns a Series indexed by category with the margin as a percentage rounded to 2 decimals, sorted from highest to lowest margin.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
sales = pd.DataFrame({
"category": ["Grocery", "Grocery", "Fashion", "Fashion", "Electronics"],
"revenue": [1000.0, 3000.0, 500.0, 1500.0, 8000.0],
"cost": [800.0, 2100.0, 300.0, 1200.0, 7600.0],
})- Step 1: Sum revenue and cost per category *first*. Ratios of sums and averages of ratios are different numbers, and finance wants the former.
- Step 2: The margin formula `(revenue - cost) / revenue * 100` is applied once per category on the aggregated totals.
- Step 3: `round(2)` matches reporting precision and `sort_values(ascending=False)` puts the healthiest category first.
def margins(df):
grouped = df.groupby("category")[["revenue", "cost"]].sum()
margin = (grouped["revenue"] - grouped["cost"]) / grouped["revenue"] * 100
return margin.round(2).sort_values(ascending=False)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