← All Python interview questions
Validate a join before you trust the numbers
MediumPandas — JoinsRazorpayDeloitte
Revenue looked 30% too high after a join because the customer table had duplicate IDs.
Write safe_merge(orders, customers) that returns a dict with keys rows, unmatched and duplicate_keys: the row count of a left join on customer_id, the number of orders with no matching customer, and the number of customer_id values that appear more than once in customers.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
orders = pd.DataFrame({
"order_id": [1, 2, 3, 4, 5],
"customer_id": [10, 11, 12, 13, 11],
"amount": [500, 900, 250, 1200, 700],
})
customers = pd.DataFrame({
"customer_id": [10, 11, 11, 12],
"city": ["Mumbai", "Delhi", "Delhi", "Pune"],
})- Step 1: Count duplicate keys on the right table *before* merging — that is the number that explains any unexpected row growth.
- Step 2: `how='left'` keeps every order even when no customer matches, so nothing silently disappears from revenue.
- Step 3: `indicator=True` adds a `_merge` column; counting `left_only` gives the unmatched orders without a second pass.
- Step 4: Casting to `int` returns plain Python numbers rather than NumPy scalars, which serialise cleanly into reports.
def safe_merge(orders, customers):
duplicate_keys = int(customers["customer_id"].duplicated().sum())
merged = orders.merge(customers, on="customer_id", how="left", indicator=True)
unmatched = int((merged["_merge"] == "left_only").sum())
return {
"rows": int(len(merged)),
"unmatched": unmatched,
"duplicate_keys": duplicate_keys,
}Learn the concept first
Stuck on Pandas — Joins? These free Python lessons teach it step by step.
More Pandas — Joins 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