Build a Region-Level Revenue Summary with Pandas
SQL & DataModel answerLast updated
Merge two DataFrames on a shared key, then aggregate transaction amounts by region to produce a sorted summary of total and average spend.
Region-Level Revenue Summary
Your analytics team stores customer data and purchase records in two separate tables. You need to combine them and produce a regional breakdown of revenue.
Input Tables
customers
| customer_id | region |
|---|---|
| 1 | EU |
| 2 | APAC |
| 3 | EU |
purchases
| purchase_id | customer_id | amount |
|---|---|---|
| 101 | 1 | 80.0 |
| 102 | 1 | 40.0 |
| 103 | 2 | 55.0 |
Task
Write a Python function using pandas that:
- Joins
purchasestocustomersoncustomer_id, retaining only purchases that have a matching customer record. - Groups the result by
regionand computes two metrics: the total purchase amount and the average purchase amount per transaction. - Returns a DataFrame with columns
region,total_amount, andavg_amount, sorted bytotal_amountdescending.
Expected Output
| region | total_amount | avg_amount |
|---|---|---|
| EU | 120.0 | 60.0 |
| APAC | 55.0 | 55.0 |
What is expected
- Correct join semantics (only matched rows survive).
- Clean, flat column names — no MultiIndex.
- Sorted output that is deterministic, including ties.
- A discussion of data-quality edge cases: nulls, duplicate keys, orphan rows, and the distinction between average-per-transaction vs. average-per-customer.
Hints
Hint 1
Which join type keeps only purchases that have a matching customer? Think about what happens to customer 3, who has no purchases, and to a purchase whose customer_id doesn't exist in the customers table.
Hint 2
Named aggregation syntax — agg(total_amount=("amount", "sum"), avg_amount=("amount", "mean")) — produces flat column names directly and avoids the MultiIndex you get from passing a list of functions. Try it instead of the dict form.
Hint 3
After sorting by total_amount, add a secondary sort key to make the output deterministic when two regions have identical totals. Also consider using validate="many_to_one" in merge so a duplicated customer_id in the customers table raises an error rather than silently inflating your totals.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a three-step pipeline: join, aggregate, sort. Every step has a subtle choice that separates a strong answer from a correct-but-naive one.
Step 1 — Choose the right join
"Only purchases with a matching customer" means an inner join. Consequences worth stating out loud:
- Customer 3 (EU) has no purchases and contributes zero rows. If the business wants every region in the output — including those with no revenue — switch to a left join from
customersand fill nulls with 0. - A purchase whose
customer_idis absent fromcustomersis silently dropped. In a production pipeline you should count these orphan rows and log them, because a large number signals an upstream data problem.
Step 2 — Aggregate cleanly
Use named aggregation inside .agg(). Passing a dict of lists produces a MultiIndex on the columns, which requires an extra flattening step and is easy to get wrong. Named aggregation gives you flat, readable names in one go.
The average is computed per transaction, not per customer. (EU has two purchases of 80 and 40, so the average is 60, not 120.) If the business wants the average revenue per customer, you need a two-level aggregation: sum per customer first, then average across customers within a region. It is worth asking which one the stakeholder actually needs.
Step 3 — Sort deterministically
Sort descending on total_amount. Add region as a secondary sort key so ties always produce the same row order. Report outputs should be reproducible — interviewers notice when you think about this.
SQL equivalent
Useful to mention in an interview so you show the two languages are solving the same problem:
SELECT c.region,
SUM(p.amount) AS total_amount,
AVG(p.amount) AS avg_amount
FROM purchases p
JOIN customers c ON c.customer_id = p.customer_id
GROUP BY c.region
ORDER BY total_amount DESC;
Solution
import pandas as pd
def region_revenue_report(
customers: pd.DataFrame,
purchases: pd.DataFrame,
) -> pd.DataFrame:
"""
Inner-join purchases to customers on customer_id, then return total
and average transaction amount per region, sorted by total descending.
Parameters
----------
customers : DataFrame with columns [customer_id, region]
purchases : DataFrame with columns [purchase_id, customer_id, amount]
Returns
-------
DataFrame with columns [region, total_amount, avg_amount]
"""
merged = purchases.merge(
customers[["customer_id", "region"]],
on="customer_id",
how="inner",
validate="many_to_one", # raises MergeError if customer_id is duplicated in customers
)
report = (
merged
.groupby("region", as_index=False)
.agg(
total_amount=("amount", "sum"),
avg_amount=("amount", "mean"),
)
.sort_values(
["total_amount", "region"],
ascending=[False, True],
kind="mergesort", # stable sort preserves relative order of equal keys
)
.reset_index(drop=True)
)
return report
if __name__ == "__main__":
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"region": ["EU", "APAC", "EU"],
})
purchases = pd.DataFrame({
"purchase_id": [101, 102, 103],
"customer_id": [1, 1, 2],
"amount": [80.0, 40.0, 55.0],
})
print(region_revenue_report(customers, purchases))
# region total_amount avg_amount
# 0 EU 120.0 60.0
# 1 APAC 55.0 55.0
Why each choice matters
how="inner"— the pandas default, but writing it out signals intent.validate="many_to_one"— without this, a duplicatedcustomer_idin the dimension table silently duplicates purchase rows and inflates every total. This is one of the most common real-world bugs in join pipelines and easy to miss.- Selecting only needed columns before merging (
customers[["customer_id", "region"]]) reduces memory usage. At scale, carrying unused columns through a large merge is wasteful. as_index=Falsekeepsregionas a regular column rather than the index, so noreset_indexis needed aftergroupby— though a finalreset_index(drop=True)aftersort_valuesgives a clean 0…n-1 row index.- Secondary sort on
regionmakes output deterministic when totals tie.
Complexity
| Step | Time | Space |
|---|---|---|
| Merge | O(C + P) | O(P) for merged frame |
| Groupby | O(P) | O(R) for R regions |
| Sort | O(R log R) | O(R) |
| Overall | O(C + P + R log R) | O(P) |
C = customers, P = purchases, R = distinct regions. In practice R ≪ P so the sort is negligible.
Edge cases to raise
- Null
amount:sumandmeanskip NaN by default. If nulls should count as 0,fillna(0)before aggregating. - Null
region:groupbysilently drops NaN keys. Passdropna=Falseto include an "unknown" bucket. - Dtype mismatch on
customer_id(int in one table, string in the other): merge returns zero rows with no error. Cast to a consistent type first. - Empty DataFrames: the function returns an empty DataFrame with the correct columns, which is fine — just make sure downstream code handles it.
- Currency precision: floating-point sums accumulate rounding error. For display,
.round(2); for storage, consider integer cents.
Common mistakes
- Using
how="left"orhow="outer"without justification, which violates the "matching customer only" requirement. - Sorting ascending, or sorting by
avg_amountinstead oftotal_amount. - Using dict-of-lists aggregation and leaving a MultiIndex in the columns.
- Assuming the average means per-customer rather than per-transaction, without asking.
- Skipping the
validateargument and missing the duplicate-key bug entirely.