pandas · difficulty ◆◆
pandas merge() — join two DataFrames like SQL, without the surprises
merge() is SQL's JOIN with a paper trail: always ask how= and validate= before you trust the row count.
The join that quietly turned 3 invoice rows into 5 — and the one kwarg that would have caught it.
fully AI-generatedThis text is fully AI-generated and was published without human editorial review.$ df.merge()- 12
- Parameters
- 0.17.0
- indicator since
- 1.2.0
- how="cross" since
- 3.0
- Anti joins since
In the DataFrame.merge signature of pandas 3.0.3, excluding self
2015 — the _merge column is a Categorical
December 2020, for cartesian products
left_anti / right_anti in the how= parameter
What it does
merge() lines up two DataFrames by key and glues their columns together. You say which keys (on=, left_on=/right_on=, or left_index=/right_index=) and which direction (how="inner" by default, or left/right/outer/cross). Unlike join(), merge() happily matches column-to-column, so the index plays no part unless you ask for it.
Why it matters
Reporting almost never lives in one table: orders sit in one export, customer names in another, quotas in a third spreadsheet someone emails you. merge() is how those become one frame you can group. And because it can also tell you what did NOT match (indicator=True) or refuse to run when keys are dirty (validate=), it doubles as a data-quality check before you ship numbers to anyone.
Example
$ import pandas as pd
orders = pd.DataFrame({
"order_id": [1001, 1002, 1003, 1004, 1005],
"customer_id": ["C-07", "C-12", "C-07", "C-31", "C-44"],
"total": [240.0, 89.5, 1310.0, 42.0, 610.0],
})
customers = pd.DataFrame({
"customer_id": ["C-07", "C-12", "C-31", "C-88"],
"company": ["Yanbu Fabricators", "Jubail Marine", "Red Sea E&I", "Gulf Valves"],
"region": ["West", "East", "West", "East"],
})
print(orders.merge(customers, on="customer_id", how="left")) order_id customer_id total company region
0 1001 C-07 240.0 Yanbu Fabricators West
1 1002 C-12 89.5 Jubail Marine East
2 1003 C-07 1310.0 Yanbu Fabricators West
3 1004 C-31 42.0 Red Sea E&I West
4 1005 C-44 610.0 NaN NaNhow="left" keeps every order even when the customer is missing (C-44), filling the right-hand columns with NaN. That is exactly the shape you want for a revenue report: never lose a transaction because a lookup table is incomplete.
$ import pandas as pd
orders = pd.DataFrame({
"order_id": [1001, 1002, 1003, 1004, 1005],
"customer_id": ["C-07", "C-12", "C-07", "C-31", "C-44"],
"total": [240.0, 89.5, 1310.0, 42.0, 610.0],
})
customers = pd.DataFrame({
"customer_id": ["C-07", "C-12", "C-31", "C-88"],
"company": ["Yanbu Fabricators", "Jubail Marine", "Red Sea E&I", "Gulf Valves"],
"region": ["West", "East", "West", "East"],
})
audit = orders.merge(customers, on="customer_id", how="outer", indicator=True)
print(audit.groupby("_merge", observed=True).agg(rows=("order_id", "size"), revenue=("total", "sum"))) rows revenue
_merge
left_only 1 610.0
right_only 1 0.0
both 4 1681.5how="outer" plus indicator=True is a reconciliation tool. One order belongs to an unknown customer (left_only), one customer never ordered (right_only, hence revenue 0), and the 4 matched rows split the same way they would in the plain left join. I run this before believing any total.
$ import pandas as pd
sales = pd.DataFrame({
"rep_id": ["R1", "R1", "R2", "R3"],
"quarter": ["Q1", "Q2", "Q1", "Q2"],
"amount": [12_000, 15_500, 8_200, 19_000],
})
targets = pd.DataFrame({
"rep": ["R1", "R2", "R3"],
"quarter": ["Q1", "Q1", "Q2"],
"quota": [10_000, 9_000, 18_000],
})
booked = sales.merge(
targets,
left_on=["rep_id", "quarter"],
right_on=["rep", "quarter"],
how="left",
)
print(booked[["rep_id", "quarter", "amount", "quota"]]) rep_id quarter amount quota
0 R1 Q1 12000 10000.0
1 R1 Q2 15500 NaN
2 R2 Q1 8200 9000.0
3 R3 Q2 19000 18000.0Composite keys: left_on/right_on accept lists, and the key columns can have different names. R1's Q2 row has no quota entry, so quota is NaN — comparing against NaN gives False, so a missing target silently reads as 'missed'. Fill it deliberately if that is not what you mean.
$ import pandas as pd
price_q1 = pd.DataFrame({"part": ["VLV-100", "VLV-200"], "price": [410.0, 980.0]})
price_q2 = pd.DataFrame({"part": ["VLV-100", "VLV-200"], "price": [395.0, 1010.0]})
print(price_q1.merge(price_q2, on="part", suffixes=("_q1", "_q2"))) part price_q1 price_q2
0 VLV-100 410.0 395.0
1 VLV-200 980.0 1010.0Two frames with the same column name: suffixes decides who gets _x/_y. Naming them price_q1/price_q2 at merge time beats renaming afterwards, because the label tells the next reader where the column came from.
$ import pandas as pd
invoices = pd.DataFrame({
"invoice": ["INV-1", "INV-2", "INV-3"],
"part": ["VLV-100", "VLV-200", "VLV-100"],
"qty": [2, 1, 5],
})
catalog = pd.DataFrame({
"part": ["VLV-100", "VLV-100", "VLV-200"],
"price": [410.0, 999.0, 980.0],
})
print("rows after sloppy join:", len(invoices.merge(catalog, on="part")))
try:
invoices.merge(catalog, on="part", validate="many_to_one")
except pd.errors.MergeError as err:
print("MergeError:", err)rows after sloppy join: 5
MergeError: Merge keys are not unique in right dataset; not a many-to-one merge
Duplicates in right:
part
VLV-100 ...The duplicate-key trap in one screenshot. A catalog with a repeated part code turns 3 invoices into 5 rows — no error, no warning, just inflated quantity. validate="many_to_one" turns that silence into a MergeError pointing at the offending key.
Common flags
- how=
- "inner" (default), "left", "right", "outer", "cross"; "left_anti"/"right_anti" arrived in pandas 3.0.
- on=
- Key column(s) present in both frames with the same name — the common case.
- left_on= / right_on=
- Different key names on each side; accepts lists for composite keys.
- indicator=True
- Adds a _merge column tagging each row both / left_only / right_only. Pass a string to rename it.
- validate=
- "one_to_one", "1:1", "one_to_many", "many_to_one", "m:m" — raises MergeError when the keys break the promise.
- suffixes=("_x", "_y")
- Renames overlapping non-key columns instead of letting them collide.
- sort=
- Sorts the merged keys; outer joins already sort lexicographically, inner/left preserve left key order.
History
Where it came from
merge() has been pandas' answer to SQL JOIN since the earliest releases, and it grew features the way most pandas APIs did: by request. indicator arrived in 0.17.0 (2015) after issue #8790 asked for a per-row merge-status flag in November 2014. how="cross" landed in 1.2.0 (December 2020). Anti joins (left_anti/right_anti) finally showed up in pandas 3.0, closing issue #42916.
One design note
The default is how="inner" — the strictest and quietest option. In SQL you usually spell the join type out; in pandas people forget, get the intersection, and then wonder where half their rows went. If a merge result ever looks too small, check whether you omitted how=.
Under the hood
Under the hood: a hash join, not a nested loop
pandas factorizes the right frame's key columns into integer codes, builds a hash table from them, then probes it with the left frame's factorized keys — the same shape as a database hash join, so cost scales roughly with rows rather than rows squared. That is why how="inner" and how="left" can preserve left key order cheaply while how="outer" sorts keys lexicographically: the outer path has to union both key sets before it can align them. The price is memory — the hash table plus both key arrays live in RAM at once, which is where wide frames and repeated merges of the same lookup inside a loop start to hurt.
Fun facts
Pros & cons
pros
- + Maps directly onto SQL JOIN, so existing relational intuition transfers in one step.
- + indicator and validate turn a join into an auditable reconciliation instead of a guess.
- + Handles column-to-column, column-to-index and composite keys in one method.
cons
- − Silently duplicates rows when keys are non-unique — the most common way pandas reports get wrong totals.
- − NaN keys match each other, diverging from SQL join semantics.
- − Every merge materialises a new frame, so chaining many of them on big tables costs real memory.
Takeaways
- 1Write how= explicitly every time; the inner default is how rows disappear silently.
- 2Run the first merge with indicator=True to see what failed to match.
- 3Add validate="m:1" (or another cardinality) whenever the lookup table should be unique.
- 4Use suffixes to label provenance (price_q1/price_q2) rather than renaming later.
- 5Outer joins sort keys; left/inner keep left order — do not rely on sort for reporting order.
Related commands
archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →
