EN VI

pandas Merge: Why Your Row Count Changes

By ··8 min read

Short answer

A pandas merge changes the row count in three common ways. The right table can have several rows for one key, which repeats the left row. Missing keys, NaN, are matched to each other, unlike in SQL. A filter after a left merge removes the unmatched rows. Check the shape after each merge, and pass validate to stop an unexpected one-to-many match.

In the pandas basics post we filtered and grouped one table. Real questions need two tables, so we reach for merge. On a customer table with a few hundred thousand rows, a merge can add or drop rows unnoticed. The code still runs, and the total still looks reasonable. To avoid this, we first compare the two main kinds of merge, and then we look at three ways a row count goes wrong. All examples use the same three small tables.

import numpy as np
import pandas as pd

customers = pd.DataFrame({
    "customer_id": [1, 2, 3, 4, 5],
    "name": ["Ruby Hoang", "Ethan Vu", "Kevin Do", "Sophie Ly", "Daniel Tran"],
})
orders = pd.DataFrame({
    "order_id": [1001, 1002, 1003, 1004, 1005, 1006],
    "customer_id": [1, 2, 1, 3, 2, 4],
    "total_amount": [15000000, 8000000, 12000000, 20000000, 5000000, 18000000],
    "status": ["paid", "paid", "cancelled", "paid", "paid", "paid"],
})
items = pd.DataFrame({
    "order_id": [1001, 1001, 1001, 1002, 1003],
    "product": ["Keyboard", "Monitor", "Mouse", "Cable", "Dock"],
    "item_amount": [5000000, 7000000, 3000000, 8000000, 12000000],
})

Inner and left merge: what happens to a customer with no orders

By default, merge keeps only the keys that appear on both sides, which is the same as INNER JOIN. With how="left", it keeps every row of the left table and fills the right side with NaN when nothing matches. Daniel Tran has no orders, so the two kinds differ by one row.

print(len(customers.merge(orders, on="customer_id")))                # 6
print(len(customers.merge(orders, on="customer_id", how="left")))    # 7

m = customers.merge(orders, on="customer_id", how="left", indicator=True)
print(m.loc[m["_merge"] == "left_only", "name"].tolist())            # ['Daniel Tran']

The indicator=True option adds a _merge column that says where each row came from. Rows marked left_only are the customers with no match, so this is a quick way to list them.

Trap 1: one row on the left becomes several

Order 1001 has three items. When we merge orders with items, that order becomes three rows, and total_amount repeats on each of them. We call this fan-out, which means one row fans out into several after the merge. A sum then counts the order three times.

print(orders["total_amount"].sum())                  # 78000000

# WRONG: total_amount repeats on every item row
joined = orders.merge(items, on="order_id", how="left")
print(len(joined), joined["total_amount"].sum())    # 8 108000000

# right: summarise the many side first, then merge
per_order = items.groupby("order_id", as_index=False).agg(n_items=("product", "count"))
ok = orders.merge(per_order, on="order_id", how="left")
print(len(ok), ok["total_amount"].sum())            # 6 78000000

To stop this at the source, we pass validate. With "one_to_many", pandas accepts the merge only if the left keys are unique. With "one_to_one", it raises a MergeError here, because order_id repeats in items.

orders.merge(items, on="order_id", validate="one_to_one")    # raises MergeError
orders.merge(items, on="order_id", validate="one_to_many")   # passes

Trap 2: missing keys match each other

In SQL, a NULL key never matches another NULL. In pandas, it does. If both tables have a row with a missing customer_id, those two rows are joined. The pandas documentation notes that this differs from the usual SQL behaviour, so we drop missing keys on one side when they should not match.

a = pd.DataFrame({"customer_id": [1, np.nan], "x": ["a", "b"]})
b = pd.DataFrame({"customer_id": [1, np.nan], "y": ["c", "d"]})

# WRONG: the two missing keys are matched, so row "b" gets y = "d"
print(a.merge(b, on="customer_id"))

# right: drop missing keys from the right table first
b2 = b.dropna(subset=["customer_id"])
print(a.merge(b2, on="customer_id", how="left"))     # row "b" gets y = NaN

Trap 3: a filter after a left merge drops customers

Say we want every customer, with paid orders only. For Daniel Tran, status is NaN after the merge, and NaN == "paid" is false. As a result, the filter removes him, and the left merge no longer keeps every customer. Filtering the orders before the merge fixes this.

# WRONG: the filter removes customers with no order
wrong = customers.merge(orders, on="customer_id", how="left")
wrong = wrong[wrong["status"] == "paid"]
print(wrong["name"].nunique())   # 4 of 5 customers

# right: filter the orders first, then merge
paid = orders[orders["status"] == "paid"]
right = customers.merge(paid, on="customer_id", how="left")
print(right["name"].nunique())   # 5 of 5 customers

Three checks before you trust a merge

  1. Print len() of both tables and of the result. If the result is longer than the left table, find out why.
  2. Check that the key is unique on the side you expect to be "one", with df["key"].is_unique.
  3. Compare a total from the merged table with the same total from its source table.

Frequently asked questions

Why does my pandas merge return more rows than the left table?

The right table has several rows for some keys, and each match produces its own output row. Summarise the right table to one row per key before the merge, or pass validate to catch it.

What is the difference between merge and join in pandas?

merge matches on columns by default. join is a shortcut that matches on the index. Both can produce the same result, and merge is the more explicit choice.

Do NaN keys match in a pandas merge?

Yes. Unlike SQL, pandas matches missing keys to each other. Drop the missing keys first if they should not match.

References

Keep learning, step by step.

Each lesson in Learn has a business context, a runnable example and a result check, so you practise this habit on real questions.