Merge orders to customers without letting a duplicate key fan out and inflate the total — how?
orders (one row per order, with amount) is merged to customers on customer_id to attach a region. A duplicate customer_id in customers would fan the orders out and inflate SUM(amount). Merge so a fan-out fails loudly, and flag any unmatched orders.
import pandas as pd
def merge_safe(orders: pd.DataFrame, customers: pd.DataFrame) -> pd.DataFrame:
# your code here
Write the implementation.
Pass validate='many_to_one': pandas checks the right key is unique and raises MergeError on a fan-out instead of silently duplicating orders and inflating SUM(amount). Add indicator=True and filter _merge == 'left_only' for unmatched orders — both catch it at merge time.
- ✗Assuming a left join alone prevents a fan-out from duplicate right keys
- ✗Getting the validate direction backwards (
one_to_manyhere) - ✗Reading unmatched orders from
right_onlyinstead ofleft_only
- →What exactly does
validate='one_to_one'assert versusmany_to_one? - →How would you dedupe
customersif a fan-out is expected but unwanted?
validate='many_to_one' asserts the right key is unique, so a duplicate customer_id raises MergeError at merge time rather than fanning the orders out and inflating the total. indicator=True adds a _merge column; 'left_only' rows are orders with no matching customer.
import pandas as pd
def merge_safe(orders: pd.DataFrame, customers: pd.DataFrame) -> pd.DataFrame:
return orders.merge(
customers[['customer_id', 'region']],
on='customer_id',
how='left',
validate='many_to_one',
indicator=True,
)
Audit the unmatched orders with result[result['_merge'] == 'left_only'] before dropping the _merge column.