pandas merge and join: inner, left and outer — and what to do when rows double
pd.merge combines two tables on a shared key and gives you explicit control over the join columns, while DataFrame.join is a shortcut that joins on the index with how='left' by default. The how argument — inner, left, right or outer — decides which keys survive, and the row count only grows when a key repeats on one or both sides. This page covers the four options and the checks that explain a merge that doubles your rows.
What is the difference between merge and join in pandas?
pd.merge is a module-level function: it takes two tables and returns a third, matching rows by one or more keys. DataFrame.join is a method on the DataFrame itself, built to combine on the index with how='left' as the default. People coming from SQL call both of them joins, but in pandas it is merge that gives you explicit control over which columns act as keys.
The most common form is pd.merge(orders, customers, on='customer_id', how='left'). The result depends less on the syntax and more on how the key is distributed across the two tables — which is where row counts surprise people.
- pd.merge: module function; accepts on=, left_on=, right_on=, suffixes=, validate= and indicator=.
- DataFrame.join: shortcut that joins on the index; default how='left'.
- Both accept the same how values: inner, left, right and outer.
- pd.merge defaults to how='inner'; DataFrame.join defaults to how='left'.
When should you use inner, left, right or outer?
how defines which keys survive the match. If you only want cases where the key exists on both sides, use inner. If you want to keep the left table intact and bring in right-side information whenever it exists, use left.
outer deserves separate attention for row counts: it keeps the union of keys from both sides, so the result can be larger than either input table, and it produces NaN in both directions. That makes it good for auditing a registry and risky for feeding a report without a check first.
- inner: only keys present on both sides; the default for pd.merge.
- left: every key from the left table; unmatched right-side values become NaN.
- right: mirror of left, keeping the right table whole.
- outer: union of keys; fills NaN on both sides and is usually the option that grows the row count most.
Why does the number of rows double after a merge?
A row on the left with key A and two rows on the right with the same key A produce two rows in the result, not one. Two on each side produce four. The merge does not pick a winner: it replicates every allowed combination inside the group, exactly like a many-to-many JOIN in SQL.
When the repetition sits on one side only (one-to-many), growth is proportional and often legitimate — an order table joined to its line items. The problem appears when the duplication is accidental: the same customer registered twice, a product listed under two names, dates stored at different granularity in each table.
Keys with trailing spaces, different capitalisation or different types (a number in one table, text in the other) do not match. Under left or outer that turns into NaN; under inner the row simply disappears from the result, with no error raised.
Nulls never match each other: NaN is not equal to NaN. Decide before the merge whether null keys should be filled, dropped, or handled as a separate group.
How do you catch duplicate keys before the merge runs?
Start by measuring key uniqueness. df['key'].duplicated().sum() returns how many rows repeat a key already seen, and value_counts() shows the full distribution, exposing every key with a count above 1 on either side.
For a formal guarantee, use validate=. validate='one_to_one' raises MergeError when the key is not unique in both tables; 'one_to_many', 'many_to_one' and 'many_to_many' run the corresponding checks. It is the cheapest way to find the problem before a report goes out wrong.
After the merge, indicator=True adds a _merge column with the values 'both', 'left_only' and 'right_only'. That shows how many rows actually matched and how many were left on each side — useful both for finding dirty keys and for confirming the how you chose was the how you meant.
- Before: duplicated().sum() and value_counts() on each join key.
- During: validate='one_to_one' (or the matching cardinality) to force the error.
- After: indicator=True and reading the _merge column.
- Always compare the result's shape with the count you expected before handing the table on.
What should you do when the row count still doubles?
First decide which granularity the result should have. If the final table is one row per customer, a key that repeats on the right means you must aggregate the right side first — groupby with sum, mean, max or the latest date — and then merge the reduced table.
If the duplicates are genuinely unwanted, run drop_duplicates on the key columns before merging, but keep a copy of what you removed and inspect it by hand: sometimes the duplicate carries different information, such as two addresses for the same customer.
Confirm that both keys have the same type and are cleaned the same way: str.strip(), consistent case, and dates parsed with pd.to_datetime on both sides. A key that matches in one table and not in the other is the most common silent cause of both NaN and vanished rows.
If two tables share a column name that is not a key, suffixes= controls how the output names them, so you do not lose track of which column came from which side. Then validate against a number you trust: under how='left' the row count should not change unless the right side has duplicate keys.
None of this is exotic. It is data cleaning, and it decides whether the model or the dashboard built downstream can be trusted at all.
- Reduce the many side with groupby before merging.
- drop_duplicates on the key columns, keeping a copy of what was removed.
- Normalise type and text on both keys (strip, case, to_datetime).
- Use suffixes= when non-key column names collide.
- Re-check the row count after every change.
Where can you practise merge and join on real data?
Merge logic sits inside the Pandas coverage of the Python for Data Science and Analytics course, which runs from zero to advanced across three main modules — Basic, Intermediate and Advanced — plus bonus modules. Data cleaning and preparation, outlier detection and visualisation are taught alongside it, so the merge is practised inside the workflow that produces a dataset rather than as an isolated exercise.
The course includes guided exercises, high-quality recorded lessons you watch at your own pace, real market projects for a portfolio, lifetime access with no expiry, a certificate of completion and an exclusive community for networking. It closes with an end-to-end final project: exploratory analysis and machine learning. You do not need to know how to program to start. The price is R$ 470, or 12 payments of R$ 20.37 on a card, through the Hotmart checkout, which also accepts boleto. Details are on python.paanalytics.net.
| how | Rows kept | Row-count risk | Typical use |
|---|---|---|---|
| inner | Only keys present in both tables | Can still grow when the key repeats on both sides | Combining tables that should share a clean key |
| left | Every row from the left table | Grows when the right-side key repeats | Enriching a main table with reference data |
| right | Every row from the right table | Grows when the left-side key repeats | When the reference table is the one you trust |
| outer | Union of keys from both sides | Grows on both sides at once | Auditing keys that exist in only one table |
Behaviour of pd.merge as documented by pandas and described in this tutorial; no pricing or competitor data used.
Learn pandas from zero to advanced, with a final project
Secure payment via Hotmart, up to 12 installments.
Enroll now Product siteFrequently asked questions
Does the order of the tables in pd.merge matter?
Yes for left and right. With how='left', the first argument is the table kept whole; swap the arguments and you get the behaviour of how='right'. Output column order also follows the argument order, and the _x / _y suffixes are assigned left to right.
What happens when both tables have a column with the same name?
If that column is not part of the join key, pandas adds suffixes — _x for the left table and _y for the right by default. Set suffixes=('_orders','_customers') to keep names readable, and inspect the output columns after the merge, since overlapping names are easy to miss.
Is merge the same as concat?
No. concat stacks tables along an axis and aligns on position or index labels; merge matches rows by key values and can combine tables with completely different columns. Use concat to append months with the same schema, and merge to bring new columns into an existing table.
How do I merge on the index instead of a column?
Use left_on= and right_on= with the index name, or set the index and call DataFrame.join, which joins on the index by default. pd.merge also accepts left_index=True and right_index=True when the key lives in the index on one or both sides.
How do I find the rows that did not match?
Run the merge with indicator=True and filter on _merge == 'left_only' or 'right_only'. With how='outer' you see both sides at once; with how='left' you see which left rows found no partner on the right.