Sub topic 7
One-to-one, one-to-many, and many-to-many merges
This chapter assumes you can build DataFrames, know what a merge key is, and have used merge with the how argument. Here you learn to predict how many rows a merge returns before you run it.
Cardinality decides the row count
Cardinality describes how many rows on each side share the same key value. Pandas does not look at it for you. For each key value, a merge pairs every matching left row with every matching right row. The result for that key has left_count * right_count rows.
| Relationship | Left rows per key | Right rows per key | Rows per key in result |
|---|---|---|---|
| One-to-one | 1 | 1 | 1 |
| One-to-many | 1 | n | n |
| Many-to-one | n | 1 | n |
| Many-to-many | m | n | m * n |
One-to-many
A customers table has one row per customer. An orders table has many rows per customer. Each customer row is repeated once for each of its orders.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Chen"],
})
orders = pd.DataFrame({
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 3, 4],
"amount": [25.0, 40.0, 15.5, 60.0],
})
result = customers.merge(orders, on="customer_id")
print(result)
print(len(result))The inner join returns 3 rows. Ana appears twice because she has two orders. Chen appears once. Ben has no orders and customer 4 has no customer record, so both are dropped.
Repeated customer values are normal here. Be careful when you sum a column that came from the "one" side, such as a customer credit limit. After the merge it is repeated on every order row, so the sum counts it too many times.
Many-to-many
A many-to-many merge happens when the key repeats on both sides. The rows multiply.
left = pd.DataFrame({"key": ["a", "a", "b"], "x": [1, 2, 3]})
right = pd.DataFrame({"key": ["a", "a", "a", "b"], "y": [10, 20, 30, 40]})
merged = left.merge(right, on="key")
print(len(merged))The key "a" appears 2 times on the left and 3 times on the right, which gives 6 rows. The key "b" gives 1 row. The total is 7.
Duplicates in both inputs usually signal a mistake, such as a key that is not as unique as you assumed. The output grows quickly. Two tables with 1,000 rows each that share one key value produce 1,000,000 rows.
How join type changes the count
The how argument changes which unmatched rows appear, but the matched rows still multiply as shown above. With how="left", a left row with no match appears once, with NaN in the right columns. A left row with matches appears once per match.
left_join = customers.merge(orders, on="customer_id", how="left")
print(len(left_join))This returns 4 rows: two for Ana, one for Ben (with NaN order columns), and one for Chen.
Check the count before you trust it
You can find duplicate keys directly. The duplicated method marks repeated values, and value_counts shows how many rows each key has.
print(orders["customer_id"].is_unique)
print(orders["customer_id"].value_counts())
print(customers["customer_id"].is_unique)is_unique is False for orders and True for customers. This tells you the merge is one-to-many with customers on the left. To make pandas enforce this, pass validate, which the next chapter covers in detail.
ok = customers.merge(orders, on="customer_id", validate="one_to_many")
print(len(ok))If the right side had duplicate keys the claim did not allow, pandas would raise MergeError instead of returning a larger table.
Common errors
- Assuming a key is unique because it looks like an ID. Real data often has repeated rows from earlier loads.
- Summing a one-side column after a one-to-many merge. Aggregate before merging, or drop the repeated values first.
- Using a left join and expecting the row count to match the left table. It matches only when the right side has unique keys.
Exercise
A left table has the key values [1, 1, 2] and a right table has the key values [1, 1, 1, 3]. How many rows does an inner merge on the key return, and how many does a left merge return?
Show answer
The inner merge returns 6 rows, because key 1 gives 2 * 3 = 6 and keys 2 and 3 have no match in the other table. The left merge returns 7 rows: the 6 matched rows plus one row for the left key 2, which has no match and gets NaN in the right columns.
Exercise
You merge a customers table (unique customer_id) with an orders table. The result has fewer rows than orders. What does that tell you about the keys, and which join type would keep every order?
Show answer
Some orders have a customer_id that is not in customers, and the inner join dropped them. A left join with orders on the left (or a right join with customers on the left) keeps every order and fills the customer columns with NaN.