Sub topic 9
Fixing dtype, missing-value, and text-matching problems in keys
This chapter assumes you can build DataFrames, select columns, and read the common pandas dtypes (int64, float64, object, string). It also assumes you know merge with on=, the four join types, and the indicator option from earlier chapters.
A merge compares key values for equality. If the values look the same to you but differ for pandas, rows silently fail to match. Most "my merge lost rows" bugs come from three sources: dtype mismatches, missing values, and inconsistent text.
How key problems show up
Key problems fail in two ways. Some raise an error, which is easy to notice. Others return fewer or more rows than you expected and give no warning, which is much worse.
| Problem | What you see | Typical fix |
|---|---|---|
| Integer key against string key | `ValueError` at merge time | Convert one side with `astype` or `pd.to_numeric` |
| Strings that differ by leading zeros | Rows missing, no error | `str.zfill` or convert both to numbers |
| Integer key against float key | Usually works, but can hide mismatches | Convert both to one numeric dtype |
| Missing values in keys | Extra matched rows, no error | Drop or fill missing keys first |
| Extra spaces or different case | Rows missing, no error | `str.strip()` and `str.lower()` |
Dtype mismatches
Suppose customer IDs are integers in one table and strings in another. This happens often when one table comes from a CSV that was read with a text column.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Chen"],
})
orders = pd.DataFrame({
"customer_id": ["1", "1", "3", "4"],
"amount": [25.0, 40.0, 15.5, 60.0],
})
try:
customers.merge(orders, on="customer_id")
except ValueError as err:
print("Merge failed:", err)pandas refuses to compare int64 with object and raises a ValueError that names both dtypes. Fix it by converting one side so both match. Convert the side that holds the more correct type. IDs that are really numbers should usually be numbers.
orders["customer_id"] = orders["customer_id"].astype("int64")
print(customers.merge(orders, on="customer_id"))astype("int64") raises an error if any value cannot be parsed, such as "N/A". When the column may contain junk, use pd.to_numeric instead:
raw = pd.Series(["1", "2", "N/A", "4"])
clean = pd.to_numeric(raw, errors="coerce").astype("Int64")
print(clean)errors="coerce" turns unparseable values into missing values. The "Int64" dtype (capital I) is the nullable integer type. It holds integers and missing values together, where plain int64 cannot. After coercion, check how many keys became missing so you know how much data you lost.
Integer and float keys
An integer column that gains a missing value becomes float64, because plain int64 cannot hold NaN. Merging int64 with float64 works when the values line up, but it hides the reason the dtypes differ. Convert both sides to Int64 before merging. That makes the intent clear and keeps whole numbers from turning into 1.0.
Strings that look like different numbers
Two string columns have the same dtype, so pandas does not complain. It compares text exactly, so "001" and "1" are different keys.
cities = pd.DataFrame({
"code": ["001", "002", "010"],
"city": ["Oslo", "Bergen", "Tromso"],
})
population = pd.DataFrame({
"code": ["1", "2", "10"],
"people": [700_000, 290_000, 77_000],
})
print(cities.merge(population, on="code", how="outer", indicator=True))Every row comes back as left_only or right_only, and none are both. Pad the short codes so both sides use the same format:
population["code"] = population["code"].str.zfill(3)
print(cities.merge(population, on="code", how="outer", indicator=True))The alternative is to convert both columns to integers. That works only when leading zeros carry no meaning. Postal codes and product codes often need the zeros kept, so padding is the safer choice.
Missing values in keys
SQL treats NULL as never equal to anything, including another NULL. pandas does the opposite: a missing key in the left table matches a missing key in the right table.
left = pd.DataFrame({"key": [1.0, None, 3.0], "x": ["a", "b", "c"]})
right = pd.DataFrame({"key": [None, 3.0], "y": ["p", "q"]})
print(left.merge(right, on="key"))The result has two rows. Row 3.0 is expected. The other row pairs b with p because both keys are NaN. That row is almost never meaningful, since two unknown values do not mean the same entity.
Check for missing keys, then decide what they mean for your data:
print(left["key"].isna().sum(), right["key"].isna().sum())
safe = left.dropna(subset=["key"]).merge(
right.dropna(subset=["key"]), on="key"
)
print(safe)If you must keep rows with missing keys, for example in a left join where every left row has to survive, drop missing keys only from the right table. The left rows with missing keys then appear with missing right-hand columns.
kept = left.merge(right.dropna(subset=["key"]), on="key", how="left")
print(kept)Filling missing keys with a placeholder such as -1 is risky. Two rows with the same placeholder would match each other, which recreates the same problem. Fill only when the placeholder is truly unique to one side.
Inconsistent text
Text keys such as emails, names, and country labels often differ in invisible ways: trailing spaces, mixed case, or different spellings. Normalize both sides with the same function.
accounts = pd.DataFrame({
"email": ["[email protected] ", "[email protected]"],
"plan": ["pro", "free"],
})
regions = pd.DataFrame({
"email": ["[email protected]", "[email protected]"],
"region": ["EU", "US"],
})
def normalize(series):
return series.str.strip().str.lower()
accounts = accounts.assign(email=normalize(accounts["email"]))
regions = regions.assign(email=normalize(regions["email"]))
print(accounts.merge(regions, on="email"))Defining one function and applying it to both sides keeps the rules identical. If you clean the two sides with separate code, the rules tend to drift apart.
A few more rules help:
- Use
str.casefold()instead ofstr.lower()when text may contain non-English letters. It handles cases such as Germanß. - Use
str.replace(r"\s+", " ", regex=True)to collapse repeated inner spaces. - Characters that look alike can still differ. A non-breaking space is not a normal space, and
str.strip()does remove it, but an accented letter written as two code points does not equal the single-code-point form.unicodedata.normalize("NFC", text)unifies those. - Do not overwrite the original column if you need it later. Create a helper column such as
email_key, merge on it, and drop it after.
accounts["email_key"] = accounts["email"].str.strip().str.lower()Normalization fixes systematic differences only. Spellings like "USA" against "United States" need a lookup table, which you can apply with Series.map before merging.
A reusable key audit
Before any important merge, run a short report on the keys. It catches all three problem types in one place.
def audit_keys(left, right, key):
print("dtypes:", left[key].dtype, "vs", right[key].dtype)
print("missing:", left[key].isna().sum(), "vs", right[key].isna().sum())
print("duplicates:", left[key].duplicated().sum(), "vs",
right[key].duplicated().sum())
merged = left.merge(right, on=key, how="outer", indicator=True)
print(merged["_merge"].value_counts())
return merged
audit_keys(cities, population, "code")Read the output in this order:
- Differing dtypes mean you need a conversion before anything else.
- Missing keys mean you need to decide whether they should match each other.
- Many
left_onlyandright_onlyrows when you expect overlap point to a text mismatch. Print a few unmatched keys from each side withmerged.loc[merged["_merge"] != "both", key].head()and compare them by eye. The difference is usually visible inrepr, so useprint(repr(value))to reveal hidden spaces.
Summary of habits
- Compare the key dtypes before every merge, and convert to one dtype on purpose.
- Prefer
pd.to_numeric(..., errors="coerce")overastypefor untrusted text, then count the new missing values. - Remove or handle missing keys, because pandas matches them to each other.
- Normalize text with one shared function, and keep zero padding where the zeros mean something.
- Use
indicator=Trueto see unmatched rows after a merge, andvalidateto confirm the expected cardinality.
Exercise
Two tables have a sku column. In stock it is stored as strings like "007" and "042". In sales it is stored as the integers 7 and 42. Write the code that merges them so both SKUs match, and say which side you convert and why.
Show answer
Convert the integer side to zero-padded strings, because the leading zeros are part of the SKU format and cannot be recovered from integers without guessing the width.
stock = stock.assign(sku=stock["sku"].str.strip())
sales = sales.assign(sku=sales["sku"].astype(str).str.zfill(3))
result = stock.merge(sales, on="sku", how="outer", indicator=True)
Then check that result["_merge"] has no unexpected left_only or right_only rows. Converting stock to integers would also work if the zeros never matter, but padding is safer when the width can vary elsewhere in the data.
Exercise
A left table has 5 rows where key is NaN, and the right table has 4 rows where key is NaN. You run an inner merge on key. How many rows come from the missing keys, and how do you prevent them?
Show answer
20 rows (5 x 4), because pandas matches NaN to NaN and produces every pairing. Prevent them by dropping missing keys from one or both sides before merging, for example left.dropna(subset=["key"]).merge(right.dropna(subset=["key"]), on="key").