Sub topic 3
Catching Merge Mistakes and Choosing Other Combination Methods
Assume you know basic pandas DataFrames, indexes, column selection, and common pandas dtypes. This chapter focuses on checking joins and choosing alternatives to merge.
Validate and audit a merge
A merge can run successfully while producing incorrect rows. validate checks the expected relationship between keys. For example, if each customer should appear once in customers and many times in orders, use one_to_many.
import pandas as pd
customers = pd.DataFrame({"customer_id": [1, 2]})
orders = pd.DataFrame({
"customer_id": [1, 1, 3],
"amount": [25, 40, 15],
})
try:
result = customers.merge(
orders,
on="customer_id",
how="left",
validate="one_to_many",
indicator=True,
)
print(result)
except pd.errors.MergeError as error:
print("Unexpected key relationship:", error)indicator=True adds _merge. Its values show whether each row matched both tables, came only from the left table, or came only from the right table. This is useful for auditing unmatched keys.
Fix problems in keys
Keys must have compatible values and dtypes. Convert numeric text before merging, and normalize text by trimming spaces and applying a consistent case.
customers["customer_id"] = customers["customer_id"].astype("string").str.strip()
orders["customer_id"] = orders["customer_id"].astype("string").str.strip()Handle missing keys deliberately. In pandas, missing key values can match other missing key values, unlike typical SQL behavior. Remove, fill, or separately audit missing keys when that match is unwanted.
Choose the right operation
Use concat to stack DataFrames with compatible columns. It does not match rows by a key.
combined = pd.concat([january, february], ignore_index=True)Use a cross join for every combination, such as every product and region. It can create a very large result.
combinations = products.merge(regions, how="cross")Use merge_asof for the nearest earlier timestamp or numeric value. Both inputs must be sorted by the merge key.
matched = pd.merge_asof(
trades.sort_values("time"),
quotes.sort_values("time"),
on="time",
by="ticker",
)Performance and memory
Select only needed columns before merging. Use efficient dtypes for repeated string keys, and filter rows early. Avoid cross joins unless the expected output size is acceptable. Check row counts before and after each merge, and use validate to catch accidental duplication.
Exercise
Which option checks that the left key is unique and the right key may repeat?
Show answer
Use validate="onetomany".