Sub topic 2
Merging on Differently Named and Multiple Keys
This chapter assumes basic pandas operations, DataFrame indexes, and common pandas data types. A merge combines rows from two DataFrames by matching key values.
Merging on differently named and multiple keys
Use left_on and right_on when the matching columns have different names. Pass lists to match on multiple columns. A row matches only when every key in the list matches.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 1, 2],
"region": ["East", "West", "East"],
"name": ["Ana", "Ana", "Ben"],
})
orders = pd.DataFrame({
"client_id": [1, 1, 2],
"sales_region": ["East", "West", "West"],
"amount": [25, 40, 15],
})
result = customers.merge(
orders,
left_on=["customer_id", "region"],
right_on=["client_id", "sales_region"],
)
print(result)The two key columns with different names remain in the result. Drop one pair afterward if they represent the same information.
Handling overlapping columns with suffixes
Columns other than the keys can also share names. pandas keeps both columns and adds suffixes. Set suffixes to make their sources explicit.
products = pd.DataFrame({
"product_id": [1, 2],
"name": ["Pen", "Book"],
})
items = pd.DataFrame({
"product_id": [1, 2],
"name": ["Blue pen", "Notebook"],
})
result = products.merge(
items,
on="product_id",
suffixes=("_catalog", "_order"),
)
print(result)Joining on the index with `join`
DataFrame.join is convenient when one table's index is the key. By default, it keeps every row from the calling DataFrame and matches the other table's index.
prices = pd.DataFrame(
{"price": [1.5, 12.0]},
index=pd.Index([1, 2], name="product_id"),
)
with_prices = items.join(prices, on="product_id")
print(with_prices)The on column from items is matched against prices.index. Use how="inner" or how="outer" when the default left join is not appropriate.
One-to-one, one-to-many, and many-to-many merges
Cardinality describes how often a key appears:
- One-to-one: each key appears once in both tables.
- One-to-many: a key appears once on the left and multiple times on the right.
- Many-to-many: a key appears multiple times in both tables.
For a many-to-many key, matching rows multiply. If key 1 appears twice on each side, the result contains four combinations.
Use validate to enforce the relationship you expect.
checked = customers.merge(
orders,
left_on=["customer_id", "region"],
right_on=["client_id", "sales_region"],
validate="one_to_one",
)Exercise
What happens if a key appears twice in each input DataFrame?
Show answer
The merge creates every matching pair, so two rows on each side produce four result rows.