Sub topic 7
One-to-one, one-to-many, and many-to-many merges
What you need before this chapter
This chapter assumes you can already call merge on a shared key column, and that you know the four join types (inner, left, right, outer). It also assumes you can read the index and dtypes of a DataFrame. Here you will learn to predict how many rows a merge returns, to see why that number can surprise you, and to make pandas check your assumption.
Cardinality describes the keys, not the tables
Cardinality is the relationship between key values on the two sides of a merge. It depends only on whether each side repeats key values.
| Left key | Right key | Relationship |
|---|---|---|
| Unique | Unique | one-to-one |
| Unique | Repeated | one-to-many |
| Repeated | Unique | many-to-one |
| Repeated | Repeated | many-to-many |
pandas does not label the relationship or warn you about it. It matches every left row with every right row that has the same key. The relationship is therefore your responsibility, and you can check it with a few lines of code.
You can test uniqueness directly with Series.is_unique, or count the repeated values with duplicated().sum().
The row-count rule
For each key value, an inner merge returns the number of left rows with that key multiplied by the number of right rows with that key. The total is the sum over all keys. A left join adds the left rows whose key has no match. A right join adds the unmatched right rows. An outer join adds both.
This rule produces everything below. With unique keys, every product is 1 or 0, so the merge never grows beyond the larger input. With repeated keys, the products can exceed both inputs.
One-to-one
In a one-to-one merge, each key appears at most once on each side. Splitting one entity's attributes across two tables is the typical case.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Chen"],
})
loyalty = pd.DataFrame({
"customer_id": [1, 2, 3],
"tier": ["gold", "silver", "bronze"],
})
result = customers.merge(loyalty, on="customer_id", validate="one_to_one")
print(len(result))This prints 3. The row count can never exceed the smaller table's size for an inner join, and it never changes the number of left rows for a left join. That stability is why one-to-one merges are easy to trust.
One-to-many
In a one-to-many merge, each left key appears once, and a right key may appear many times. Each left row is copied once per matching right row, and the left columns repeat on every copy.
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],
})
for how in ["inner", "left", "right", "outer"]:
print(how, len(customers.merge(orders, on="customer_id", how=how)))The output is inner 3, left 4, right 4, outer 5. The reasoning for each count:
- Inner: customer 1 has two orders and customer 3 has one, so 2 + 1 = 3. Ben has no orders and customer 4 has no customer record, so both are dropped.
- Left: the three matches plus Ben, whose order columns become
NaN. - Right: the three matches plus order 13 for customer 4, whose customer columns become
NaN. - Outer: the three matches plus Ben plus order 13.
A left join in a one-to-many merge returns at least as many rows as the left table. Customers without orders keep one row, and customers with several orders get several rows.
Many-to-many
In a many-to-many merge, the key repeats on both sides, so the rows for that key form a cross product. If key a appears twice on the left and three times on the right, you get 2 × 3 = 6 rows for a.
You can predict the count before merging. The function below counts how often each key appears on each side and applies the row-count rule.
import pandas as pd
def expected_rows(left, right, key, how="inner"):
lc = left[key].value_counts()
rc = right[key].value_counts()
inner = int((lc * rc).sum())
left_only = int(lc[~lc.index.isin(rc.index)].sum())
right_only = int(rc[~rc.index.isin(lc.index)].sum())
totals = {
"inner": inner,
"left": inner + left_only,
"right": inner + right_only,
"outer": inner + left_only + right_only,
}
return totals[how]
left = pd.DataFrame({"key": ["a", "a", "b"], "x": [1, 2, 3]})
right = pd.DataFrame({"key": ["a", "a", "a", "c"], "y": [10, 20, 30, 40]})
for how in ["inner", "left", "right", "outer"]:
actual = len(left.merge(right, on="key", how=how))
predicted = expected_rows(left, right, "key", how)
assert actual == predicted
print(how, actual)The counts are inner 6, left 7, right 7, outer 8. Multiplying the two Series aligns them on the key. Keys that exist on only one side become NaN, and sum() skips them, so only matching keys contribute to inner.
A many-to-many merge is sometimes correct, but it is more often a sign of a bad key. If you expected a one-to-many merge and one side has duplicates you did not know about, the result silently grows.
Why unexpected growth causes wrong numbers
Repeated rows break any calculation that depends on each entity appearing once. Suppose customers carry a credit limit, and you merge orders in with a left join.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"credit": [100, 200, 300],
})
orders = pd.DataFrame({
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 3, 4],
})
merged = customers.merge(orders, on="customer_id", how="left")
print(customers["credit"].sum())
print(merged["credit"].sum())The first line prints 600 and the second prints 700. Ana's credit of 100 now appears on two rows, so the sum counts it twice. Nothing raised an error, and the merge did exactly what it is defined to do.
The usual safeguards:
- Sum or average columns from the table that was on the "one" side before the merge, or after collapsing the "many" side.
- Compare
len(result)with the row count you predicted. - Count distinct entities, for example
merged["customer_id"].nunique(), instead of counting rows.
Making pandas check the relationship
The validate argument turns your assumption about cardinality into an enforced check. If the data does not match, pandas raises pd.errors.MergeError before returning a result.
| `validate` value | Short form | Requires |
|---|---|---|
| `"one_to_one"` | `"1:1"` | Unique keys on both sides |
| `"one_to_many"` | `"1:m"` | Unique keys on the left |
| `"many_to_one"` | `"m:1"` | Unique keys on the right |
| `"many_to_many"` | `"m:m"` | Nothing (no check) |
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],
})
for rule in ["one_to_one", "one_to_many", "many_to_one", "many_to_many"]:
try:
customers.merge(orders, on="customer_id", validate=rule)
print(rule, "ok")
except pd.errors.MergeError:
print(rule, "failed")Here one_to_one and many_to_one fail because orders repeats customer 1, and one_to_many and many_to_many pass. Customers is the left table, so one_to_many is the rule that matches the real relationship.
Pair validate with indicator=True when you also need to see which rows failed to match. That combination is covered in the next chapter.
Fixing an unwanted many-side
When a merge grows and you wanted one row per entity, collapse the repeated side first. Which method you choose depends on what the question asks.
- Keep one representative row, such as the latest order, with
sort_valuesanddrop_duplicates. - Summarize the repeated rows into one row per key with
groupby.
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],
})
totals = (
orders.groupby("customer_id")
.agg(total_amount=("amount", "sum"), n_orders=("order_id", "count"))
.reset_index()
)
summary = customers.merge(
totals, on="customer_id", how="left", validate="one_to_one"
)
print(summary)The grouped table has one row per customer, so the merge is one-to-one and validate confirms it. Ana gets a total of 65.0 and 2 orders, Chen gets 15.5 and 1 order, and Ben gets NaN in both new columns because he has no orders. If you want zero instead of NaN, fill those columns after the merge.
Many-to-many through a bridge table
Real many-to-many relationships, such as students and courses, are normally stored in a third table. That table has one row per pair, for example an enrollments table with student_id and course_id. You then merge in two steps: students with enrollments (one-to-many), then the result with courses (many-to-one). Each step has a clear key relationship and can carry its own validate check. This is safer than merging two tables that both repeat the same key.
Exercise
The left table has keys [x, x, y, z] and the right table has keys [x, y, y, y, w]. How many rows do an inner, a left, and an outer merge on that key return?
Show answer
Inner: x gives 2 × 1 = 2 and y gives 1 × 3 = 3, so 5 rows. Left: add the unmatched left key z, so 6 rows. Outer: also add the unmatched right key w, so 7 rows.
Exercise
You merge a customers table (unique customerid) with an orders table (repeated customerid) as customers.merge(orders, on="customerid"). Which validate value matches this relationship, and what would happen if you passed "manyto_one" instead?
Show answer
Use "onetomany", because the left key is unique and the right key repeats. Passing "manytoone" requires unique keys on the right, which orders does not have, so pandas raises MergeError.