Sub topic 9
Fixing dtype, missing-value, and text-matching problems in keys
This chapter assumes you can run merge with on=, know the four join types, and know what a dtype is. A merge can run without errors and still return wrong rows because the key columns look alike but don't compare as equal. Three causes cover most of these cases: mismatched dtypes, missing values, and inconsistent text.
Mismatched dtypes
A key that is an integer in one table and a string in the other is a common mismatch. Files read from CSV or Excel often cause it, for example when IDs are stored as text. pandas refuses to merge int64 against object and raises a ValueError.
import pandas as pd
customers = pd.DataFrame({"customer_id": [1, 2, 3], "name": ["Ana", "Ben", "Chen"]})
orders = pd.DataFrame({"customer_id": ["1", "1", "3"], "amount": [25.0, 40.0, 15.5]})
try:
customers.merge(orders, on="customer_id")
except ValueError as err:
print("Merge failed:", err)
orders["customer_id"] = pd.to_numeric(orders["customer_id"])
print(customers.merge(orders, on="customer_id"))Convert the column that is wrong, not both. pd.to_numeric is stricter than guessing: it raises on values like "N/A". Use errors="coerce" to turn those into NaN, and then deal with them as described below.
Some mismatches don't raise an error. Merging int64 against float64 works, because 1 equals 1.0. Float keys that came from arithmetic can still fail to match because of rounding. Prefer integer or string keys for identifiers.
Missing values in keys
SQL treats NULL as never equal to NULL. pandas does not. In a merge, NaN in the left key matches NaN in the right key.
left = pd.DataFrame({"key": [1.0, None], "x": ["a", "b"]})
right = pd.DataFrame({"key": [None, 1.0], "y": ["c", "d"]})
print(left.merge(right, on="key"))Both rows match, including the NaN pair. With many missing keys in both tables, this produces a large number of unwanted rows, because every NaN on the left pairs with every NaN on the right. Drop or set aside rows with missing keys first.
clean_left = left.dropna(subset=["key"])
clean_right = right.dropna(subset=["key"])
print(clean_left.merge(clean_right, on="key"))Inconsistent text
Text keys fail on small differences: trailing spaces, mixed case, or different spellings. "[email protected] " and "[email protected]" are different strings. Build a normalized key column and merge on that. The original columns stay unchanged.
left = pd.DataFrame({
"email": ["[email protected] ", "[email protected]"],
"plan": ["pro", "free"],
})
right = pd.DataFrame({
"email": ["[email protected]", "[email protected]"],
"city": ["Oslo", "Lima"],
})
for df in (left, right):
df["email_key"] = df["email"].str.strip().str.lower()
merged = left.merge(right, on="email_key", suffixes=("_left", "_right"))
print(merged[["email_key", "plan", "city"]])Normalization has limits. Stripping and lowercasing fixes formatting differences. It can't fix real spelling differences such as "Jon" and "John". Those need a mapping table or a fuzzy-matching library. Normalizing can also create duplicates: if "ANA" and "ana" are two different records, they now collide, so check key.duplicated().sum() afterward.
A quick diagnosis checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError` about merging `int64` and `object` | Key stored as text in one table | `pd.to_numeric` or `astype` |
| Fewer rows than expected | Case, spaces, or formatting differences | Normalize with `.str.strip().str.lower()` |
| More rows than expected | Duplicate keys or matching `NaN` keys | `dropna`, deduplicate, or use `validate` |
| `left_only` rows in `indicator=True` output | Keys that should match but don't | Compare `dtype` and sample values of the keys |
Use indicator=True from the previous chapter to find the unmatched rows. Then print a few of their key values with repr(), which makes hidden spaces visible.
Exercise
A left join of orders onto customers returns an unexpectedly large result. Both tables have about 500 rows with a missing customer_id. What is the likely cause, and how do you fix it?
Show answer
pandas matches NaN keys to each other, so each of the 500 missing keys on the left pairs with each of the 500 on the right. That produces 250,000 extra rows. Drop the rows with missing keys in both tables before merging, using dropna(subset=["customer_id"]). You can also pass validate="one_to_many", which would raise an error on this kind of duplication.