Sub topic 8
Catching mistakes with validate and indicator
A merge can run without errors and still return the wrong rows. Duplicate keys multiply rows, and unmatched keys quietly disappear or turn into NaN. This chapter covers two checks that make those problems visible: validate, which raises an error when the key relationship is not what you expected, and indicator, which records where each output row came from.
It assumes you can call merge, that you know the four join types, and that you understand one-to-one, one-to-many, and many-to-many relationships.
Why silent merges are risky
pandas does not check whether keys are unique. If you expect one row per customer but the table has two, the merge duplicates rows. Totals computed afterwards will be too large, and nothing warns you. The two tools below turn that failure into an error or a visible label.
Checking key relationships with validate
The validate argument declares the relationship you expect. If the data breaks it, pandas raises pandas.errors.MergeError.
| Value | Meaning | Keys must be unique in |
|---|---|---|
| `"one_to_one"` or `"1:1"` | Each key appears once on both sides | Both tables |
| `"one_to_many"` or `"1:m"` | Each key appears once on the left | Left table |
| `"many_to_one"` or `"m:1"` | Each key appears once on the right | Right table |
| `"many_to_many"` or `"m:m"` | No check | Neither |
The following code uses the customers and orders tables from earlier chapters. Customer 1 has two orders, so a one-to-one check fails.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Chen"],
})
orders = pd.DataFrame({
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 3, 4],
"amount": [25.0, 40.0, 15.5, 60.0],
})
try:
customers.merge(orders, on="customer_id", validate="one_to_one")
except pd.errors.MergeError as err:
print("Merge check failed:", err)
ok = customers.merge(orders, on="customer_id", validate="one_to_many")
print(len(ok))The first merge fails because customer_id 1 is duplicated in orders. The second states the real relationship, so it succeeds and returns 3 rows.
validate checks only uniqueness. It does not check that every key has a match. A merge with validate="one_to_many" still drops customer 2 in an inner join.
Auditing matches with indicator
Use indicator=True to add a column named _merge. Its value for each row is one of three labels.
left_only: the key exists only in the left table.right_only: the key exists only in the right table.both: the key exists in both tables.
Combine it with an outer join, which keeps every row, to see all matches and misses at once.
outer = customers.merge(
orders, on="customer_id", how="outer", indicator=True
)
print(outer[["customer_id", "name", "order_id", "_merge"]])Ben (customer 2) is left_only, because he has no orders. Customer 4 is right_only, because that order has no customer record. Ana and Chen are both.
A practical audit routine
Count the labels first, then look at the unmatched rows.
print(outer["_merge"].value_counts())
orphans = outer[outer["_merge"] == "right_only"]
print(orphans)Orphan rows such as the order for customer 4 usually point to a data problem, such as a deleted customer or a key typo. Once you have investigated, you can run the final merge with the join type you actually want and drop the indicator column.
You can also rename the column by passing a string, for example indicator="source". This helps if your data already has a column called _merge.
Common errors
- Using
validate="one_to_one"on data that has legitimate repeats. Pick the relationship that matches the business rule. - Assuming
validatefinds missing matches. Useindicatorfor that. - Filtering on
_mergeafter an inner join. Inner joins drop unmatched rows, so onlybothremains. Use an outer or left join when auditing. - Forgetting that keys with mismatched dtypes or stray whitespace show up as false
left_onlyandright_onlyrows. The next chapter covers fixing these.
Exercise
You run customers.merge(orders, on="customerid", how="left", validate="onetomany", indicator=True). Which merge values can appear in the result, and why?
Show answer
Only "both" and "leftonly". A left join keeps every customer, so customers with no orders are "leftonly". Orders whose customerid has no customer row are dropped by the left join, so "rightonly" never appears. The validate setting passes because customer_id is unique in customers.
Exercise
A merge of two tables that you expect to be one-to-one returns more rows than the left table. Which argument would have caught this, and what does it raise?
Show answer
validate="onetoone" (or "1:1"). It raises pandas.errors.MergeError when a key is duplicated in either table.