KatInterview

Build a Region-Level Revenue Summary with Pandas

SQL & DataModel answer
MediumModel answerSQL & Datapandasgroupbymerge

Last 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_idregion
1EU
2APAC
3EU

purchases

purchase_idcustomer_idamount
101180.0
102140.0
103255.0

Task

Write a Python function using pandas that:

  1. Joins purchases to customers on customer_id, retaining only purchases that have a matching customer record.
  2. Groups the result by region and computes two metrics: the total purchase amount and the average purchase amount per transaction.
  3. Returns a DataFrame with columns region, total_amount, and avg_amount, sorted by total_amount descending.

Expected Output

regiontotal_amountavg_amount
EU120.060.0
APAC55.055.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.