Sub topic 8
Catching mistakes with validate and indicator
A merge that runs without an error can still return the wrong rows. Duplicate keys multiply rows, unmatched keys vanish in an inner join, and a left join fills columns with NaN. This chapter covers two merge arguments that make these problems visible: validate, which checks the key relationship before the merge, and indicator, which records where each result row came from.
It assumes you can write a basic merge, know the four join types, and understand how row counts change with duplicate keys.
Why silent mistakes happen
merge does not know what you intended. It matches keys and returns the result. Three failures are common:
- Row multiplication. A key that should be unique appears twice, so every match is duplicated.
- Row loss. An inner join drops rows whose keys have no partner. A typo or a stale lookup table can drop thousands of rows without a warning.
- Missing values. A left join keeps unmatched rows but fills the right-hand columns with
NaN. Later code may treat those as real data.
validate guards against the first. indicator helps you find the second and third.
Setting up the data
The examples use the customers and orders tables from earlier in the tutorial.
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],
})In customers, each customer_id is unique. In orders, customer 1 appears twice. The relationship is one-to-many: one customer, many orders.
Checking relationships with validate
The validate argument asserts what kind of relationship the keys should have. If the data does not match, pandas raises pandas.errors.MergeError before it returns a result.
| Value | Short form | Requires unique keys in |
|---|---|---|
| `"one_to_one"` | `"1:1"` | left and right |
| `"one_to_many"` | `"1:m"` | left only |
| `"many_to_one"` | `"m:1"` | right only |
| `"many_to_many"` | `"m:m"` | neither (no check) |
The check only looks at whether keys are unique within each table. It does not check that every key finds a partner. A merge can pass validate="one_to_many" and still drop or null out rows.
Here the declared relationship is wrong, so pandas rejects it:
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 call fails because orders has a repeated customer_id. The message says the keys are not unique in the right dataset. The second call matches the real relationship and returns 3 rows.
Catching an accidental duplicate
The real value of validate appears when a table that should be unique is not. Suppose an import added Ana to the customer table twice:
customers_dirty = pd.concat(
[customers, customers.iloc[[0]]], ignore_index=True
)
silent = customers_dirty.merge(orders, on="customer_id")
print(len(silent))
try:
customers_dirty.merge(orders, on="customer_id", validate="one_to_many")
except pd.errors.MergeError as err:
print("Caught:", err)Without validate, the merge returns 5 rows. Ana's two copies each match her two orders, giving 4 rows, and Chen adds 1. A clean merge would return 3 rows, so Ana's orders are now counted twice. Any sum of amount would be wrong, and no error appears. With validate="one_to_many", pandas finds duplicate keys in the left table and raises MergeError instead.
Choosing the right value
Choose the value from the meaning of the tables, not from what makes the code pass.
- Use
"many_to_one"for a lookup: a fact table (orders, events) joined to a reference table (customers, products). The right table must have one row per key. - Use
"one_to_many"when the left table is the reference table. It is the same relationship with the tables reversed. - Use
"one_to_one"when both tables hold one row per entity, such as two exports about the same users. - Use
"many_to_many"rarely. It does not check anything, but it tells readers you expect row multiplication.
If a check fails and you do not know why, find the duplicates directly:
dupes = customers_dirty[
customers_dirty.duplicated("customer_id", keep=False)
]
print(dupes)keep=False marks every copy of a duplicated key, not just the second one.
Tracing row origins with indicator
indicator=True adds a column named _merge to the result. For each row it holds one of three values:
left_only: the key was found only in the left table.right_only: the key was found only in the right table.both: the key was found in both tables.
The column is a categorical. This is the example from the join-types chapter, with the audit columns shown:
outer = customers.merge(
orders, on="customer_id", how="outer", indicator=True
)
print(outer[["customer_id", "name", "order_id", "_merge"]])
print(outer["_merge"].value_counts())The outer join returns 5 rows. Ana (twice) and Chen are both, Ben is left_only, and customer 4 is right_only. The value_counts() call gives 3 both, 1 left_only, and 1 right_only.
An outer join with indicator=True is a quick diagnostic even when the final merge will use another how. It shows how well two tables line up before you decide what to keep.
Naming the column
Pass a string to choose the column name:
named = customers.merge(
orders, on="customer_id", how="left", indicator="source"
)
print(named["source"].tolist())Use a custom name when _merge already exists in one of your tables, or when you merge several times and want to keep each indicator. If a column with the chosen name already exists, pandas raises an error.
Finding unmatched rows
Filtering on the indicator gives you an anti-join: rows from one table with no partner in the other.
check = customers.merge(
orders, on="customer_id", how="left", indicator=True
)
no_orders = check.loc[check["_merge"] == "left_only", ["customer_id", "name"]]
print(no_orders)This returns Ben, the only customer with no orders. Reverse the roles, or use how="outer" and filter on "right_only", to find orders whose customer is missing from the customer table. Those rows usually point to a data quality problem.
A small audit helper
Teams repeat the same checks, so it helps to wrap them in a function. This one reports the match counts and optionally enforces a minimum match rate.
import pandas as pd
def audit_merge(left, right, on, min_match=None):
"""Return key-match counts for an outer merge of left and right."""
check = left.merge(right, on=on, how="outer", indicator=True)
counts = check["_merge"].value_counts().to_dict()
total = len(check)
matched = counts.get("both", 0)
if min_match is not None and matched / total < min_match:
raise ValueError(
f"Only {matched} of {total} rows matched on {on!r}"
)
return counts
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],
})
print(audit_merge(customers, orders, on="customer_id"))On this data, 3 of 5 rows match, so min_match=0.5 passes and min_match=0.8 raises ValueError. Run the helper before the real merge. Run the real merge only if the counts look right.
Combining both tools
validate and indicator check different things, so use them together. A defensive lookup merge looks like this:
result = orders.merge(
customers,
on="customer_id",
how="left",
validate="many_to_one",
indicator=True,
)
assert len(result) == len(orders), "Lookup changed the row count"
missing = result[result["_merge"] == "left_only"]
print(f"{len(missing)} order(s) have no matching customer")
result = result.drop(columns="_merge")Each step has a job:
validate="many_to_one"guarantees the customer table has unique keys.- Because the right keys are unique, a left join cannot add rows, and the
assertconfirms the row count did not change. indicator=Truereveals orders that found no customer. Here that is order 13, for customer 4.- Dropping
_mergeat the end keeps the audit column out of the final table.
Limits and gotchas
validateonly checks uniqueness. It says nothing about whether keys match across tables. Useindicatorfor that.- Row-count assertions need a left join. With
how="inner", a smaller result is normal. Compare counts only when the join type should preserve them. _mergeis categorical. Comparing it to a string works, but if you concatenate results later you may get category warnings. Convert it with.astype(str)or drop it first.- Failures can come from key problems. If
validatefails when you expect unique keys, look for text that differs only in case or whitespace. Missing values in a key column can also count as duplicates of each other. - Do not leave audits in hot paths blindly. Both options add a pass over the data. On large tables the cost is small compared to the merge, but you can run the audit on a sample or once in a test.
Exercises
Exercise
You run orders.merge(customers, on="customer_id", validate="one_to_many") and get a MergeError. Which table has duplicate keys, and what value of validate matches the real relationship?
Show answer
The right table is not allowed to have duplicates under "onetomany", and here the right table is customers. But the left table, orders, has duplicate customerid values (customer 1 appears twice), which "onetomany" forbids on the left side. Since orders is the left table and many orders belong to one customer, the correct value is "manyto_one".
Exercise
Write code that merges customers and orders with a left join from customers, and prints the names of customers who have no orders. Use indicator.
Show answer
check = customers.merge(orders, on="customerid", how="left", indicator=True) print(check.loc[check["merge"] == "left_only", "name"].tolist()) This prints ['Ben'], because only Ben has no matching row in orders.
Exercise
A merge passes validate="manytoone" but the result has NaN in every right-hand column for some rows. Why did validate not catch this, and which option would?
Show answer
validate only checks that keys are unique on the sides that must be unique. It does not require every key to have a partner. Unmatched left keys in a left join give NaN values. Use indicator=True and look for left_only rows to find them.