Why a pandas merge adds rows and how to find the duplicate keys
Trace extra rows after a pandas merge to the keys that produced them. Predict the join size, validate a many-to-one lookup, and audit unmatched orders.
- Author
- Salon Rai
- 3 min read
A left merge in pandas keeps every row from the left table, but it can keep the same row several times. If an order matches two customer records, both matches appear in the result. To find where the extra rows came from, count occurrences of the join key on each side before you start deleting duplicates.
Follow one order through the merge
Suppose you want the sales total by customer plan. Your order table has three rows worth 30, 50 and 20 dollars. The customer table looks like a lookup, but customer A appears twice. Run this example in Python with pandas installed.
import pandas as pd
orders = pd.DataFrame({
"order_id": [11, 12, 13],
"customer": ["A", "A", "B"],
"amount": [30, 50, 20],
})
plans = pd.DataFrame({
"customer": ["A", "A", "B"],
"plan": ["basic", "pro", "basic"],
})
joined = orders.merge(plans, on="customer", how="left")
print(joined.to_string(index=False))
print(len(joined), joined["amount"].sum()) # 5 rows, 180 dollars
Order 11 occurs once with basic and once with pro. Order 12 does too. Order 13 matches one customer record and stays on one row. The resulting 180-dollar total is plausible enough to make it into a dashboard. The original total was 100. Grouping by plan after the merge only disguises the repetition by putting copies into different groups.
Predict the size from key counts
For an inner join, a key occurring twice on the left and three times on the right produces six matches. For a left join, a key present only on the left produces one output row per left row, with empty right-hand fields. For each key in the left table, multiply its left count by the larger of its right count and one. pandas merging guide
| Customer | Orders | Plan records | Rows after left merge | Extra rows |
|---|---|---|---|---|
| A | 2 | 2 | 4 | 2 |
| B | 1 | 1 | 1 | 0 |
On a large dataset, use the following immediately after defining the two frames above. It ranks keys by their contribution to the increase. A customer with many orders and one plan is unremarkable here. A duplicated key with many orders deserves attention first.
left = orders.groupby("customer", dropna=False).size().rename("left_n")
right = plans.groupby("customer", dropna=False).size().rename("right_n")
counts = left.to_frame().join(right, how="left").fillna({"right_n": 0})
counts["output_n"] = counts["left_n"] * counts["right_n"].clip(lower=1)
counts["extra"] = counts["output_n"] - counts["left_n"]
print(counts.sort_values("extra", ascending=False))
Grouping with dropna=False matters if either table contains missing identifiers. pandas can match null keys to null keys during a merge. Several missing IDs on both sides can therefore create a surprisingly large group. Check the missing-key rows separately and decide whether you have any basis for treating them as the same customer. pandas merge reference
Decide what one row on the right represents
If each plan row records a change, both of A’s rows could be legitimate. Recover the effective dates and match each order to the plan in effect when the order was placed. If the report asks for today’s plan instead, use a snapshot with an explicit as-of date. Picking the last row returned by a database without a defined ordering can assign a different plan on the next import.
If the duplicate is an ingestion error, inspect the source records, correct the lookup, and verify its key is unique. Dropping duplicates on order_id after the merge discards the evidence that two plans competed for that order. Dropping identical whole rows cannot resolve the two different labels in this example.
Enforce the relationship the report needs
Add validate="many_to_one" to the merge when the right side must contain at most one record per key. With the original plans frame it raises a merge error. Once the lookup is corrected, it documents the report’s assumption and checks it on future imports. An indicator column answers a separate question: which left-hand records had no match?
# A separately supplied, current snapshot for this report.
current = pd.DataFrame({"customer": ["A"], "plan": ["pro"]})
audit = orders.merge(
current, on="customer", how="left", validate="many_to_one", indicator=True
)
assert len(audit) == len(orders)
assert audit["amount"].sum() == orders["amount"].sum()
print(audit.loc[audit["_merge"] == "left_only", ["order_id", "customer"]])
Order 13 survives with no plan. A later group-by on plan can silently omit it because missing group keys are excluded by default. Decide whether the report should include an “unassigned” group or reject the incomplete lookup. Use the order count and amount total as reconciliation checks after producing the final report too.
Next steps
Write down the grain of each table in one sentence, such as “one row per order” and “one current plan per customer.” Use that statement to choose the merge keys and validation mode. If the resulting table will feed a model, carry the customer ID along so you can also split the dataset by customer without leaking repeat orders into the holdout.

Written by