Python • Identity and attribution
Pandas Merge Matches Null Keys: How to Prevent Incorrect Joins
When both DataFrames contain missing values in the join column, pandas.merge() can match those rows. For example, an order with no customer_id can pick up the region from a lookup row that also has no customer_id. The order count and revenue total can stay correct while the revenue gets attributed to the wrong region. validate="many_to_one" checks that the lookup keys are unique, so a single missing lookup key can still pass validation.
If a missing customer ID means the customer is unknown, filter null IDs out of the lookup table before doing a left merge. That keeps every order in the result and leaves orders with missing IDs unmatched. Use indicator=True to check unmatched rows, and label missing customer IDs separately from valid IDs that have no lookup match.
Does pandas merge match missing IDs?
Yes. Pandas can match null join keys to other null keys. A many-to-one validation checks key uniqueness; it does not prove that a missing key identifies a real customer. When missing IDs must never match, exclude them from the lookup used for joining and preserve the left-hand records with an explicit missing-ID status.
The official pandas merge reference warns about null-key matching. This differs from an ordinary SQL equality join, where NULL = NULL does not evaluate to true. A SQL join written with explicit null-safe logic is a different case.
A $50 order gets a region it does not have
In this original fictional dataset, three orders total $220. Two have valid customer IDs: C1 maps to the US and C2 to Germany. The $50 order has no customer ID. A malformed customer-lookup row also has no ID but contains “UK.” That row does not establish who placed the order.
Run the failure and the correction
import pandas as pd
orders = pd.DataFrame({
"order_id": [1, 2, 3],
"customer_id": pd.Series(["C1", None, "C2"], dtype="string"),
"amount_cents": [10000, 5000, 7000],
})
customers = pd.DataFrame({
"customer_id": pd.Series(["C1", None, "C2"], dtype="string"),
"market": ["US", "UK", "DE"],
})
# This passes uniqueness validation but matches missing IDs.
unsafe = orders.merge(customers, on="customer_id",
how="left", validate="many_to_one", indicator=True)
assert unsafe.loc[unsafe["order_id"].eq(2), "market"].iloc[0] == "UK"
assert len(unsafe) == len(orders)
assert unsafe["amount_cents"].sum() == 22000
# A missing ID is not an identity in this reporting contract.
rejected_lookup = customers[customers["customer_id"].isna()].copy()
valid_lookup = customers[customers["customer_id"].notna()].copy()
safe = orders.merge(valid_lookup, on="customer_id",
how="left", validate="many_to_one", indicator=True)
safe["match_status"] = safe["_merge"].astype("string")
safe.loc[safe["customer_id"].isna(), "match_status"] = "missing_id"
assert len(rejected_lookup) == 1
assert len(safe) == len(orders)
assert safe["amount_cents"].sum() == 22000
assert safe.loc[safe["order_id"].eq(2), "market"].isna().all()
assert safe["match_status"].tolist() == ["both", "missing_id", "both"]
print(safe[["order_id", "market", "amount_cents", "match_status"]])
Expected corrected output
order_id | market | amount_cents | match_status
1 | US | 10000 | both
2 | missing | 5000 | missing_id
3 | DE | 7000 | bothPandas may display the missing market as NaN; “missing” above is a readable label. The corrected attribution is US $100, Germany $70, and unassigned $50. The unsafe merge instead attributes that $50 to the UK. Both versions still contain three orders and $220, so total reconciliation alone misses this problem.
Why validate did not catch it
The lookup has only one row for each key, including one null key. Therefore many_to_one succeeds. The validation is doing its stated job; the business identity requirement needs an additional check. Keep validate enabled after filtering the lookup so duplicate non-null IDs still fail rather than multiplying order rows.
The rejected_lookup dataframe preserves the malformed record for review. Filtering it from the join is not evidence that it can be deleted from the source. Resolve its origin separately, then rerun under the agreed contract.
Distinguish missing IDs from unmatched valid IDs
An order with C9 absent from the lookup would be left_only, while an order without an ID is labeled missing_id. These are different investigations: one may involve a late-arriving customer record; the other requires recovering or explaining the missing identifier. The code retains both classes in a left join instead of silently dropping revenue.
Blank strings need a separate normalization rule because they are not necessarily null. Preserve original values, strip whitespace only when allowed by the identifier contract, and normalize confirmed blanks consistently before applying the null filter. Do not replace every missing ID with the same “unknown” string and then merge: that can recreate the same false match.
What about a composite key?
If identity requires both account_id and customer_id, decide whether either component may be missing. Under a contract requiring both, the lookup eligibility mask is lookup[["account_id", "customer_id"]].notna().all(axis=1). Apply validation to the complete key pair. This article’s executed fixture uses one string key; test composite keys and your actual dtypes separately.
Checks for a reliable enrichment step
- Check missingness before joining on an identifier.
- Validate the expected lookup uniqueness.
- Reconcile order count and USD totals after enrichment.
- Test that missing-ID orders receive no customer attributes.
- Report missing IDs separately from valid-but-unmatched IDs.
Validation: eight assertions passed locally in pandas 2.2.3, including the unsafe UK assignment, unchanged totals, preserved rejected lookup row, and corrected missing-ID status. These checks validate this synthetic fixture, not a production customer database.
Continue practicing
Use merge validation for duplicate lookup rows for the separate row-multiplication problem. To retain unassigned categories in a chart, follow groupby with missing keys. For identifier formatting, see preserving leading zeros in CSV imports.