skip to content

In pandas, how do you find customers who never placed an order with merge, and what did pandas 3.0 add for it?

level: middleimportance: must knowfreq 62%

answer

  1. a left merge keeps everyone
  2. a column recording each row's source
  3. left_only, right_only, both
  4. a new how value in 3.0

basics

~10 s

Left-merge customers to orders with indicator=True and keep rows whose _merge is 'left_only'. In pandas 3.0, merge(how='left_anti') returns those customers directly.

solid answer

~30 s

The classic pattern is `customers.merge(orders, on="customer_id", how="left", indicator=True)`: `indicator=True` adds a categorical column `_merge` whose values are `"left_only"`, `"right_only"` or `"both"`, and filtering `_merge == "left_only"` gives the anti-join. Because orders can repeat a customer, customers with orders appear several times, but the unmatched ones appear once. In pandas 3.0, `merge` and `DataFrame.join` accept `how="left_anti"` and `how="right_anti"`, which keep only the left (or right) rows whose key has no match, so `customers.merge(orders, on="customer_id", how="left_anti")` does it in one call. The indicator is still worth knowing: with `how="outer"` it reconciles both directions at once, for example orders that point at unknown customers.

code

python · 15 lines
python
import pandas as pd

customers = pd.DataFrame(
    {"customer_id": [1, 2, 3, 4], "name": ["Ana", "Ben", "Cy", "Dee"]}
)
orders = pd.DataFrame({"order_id": [10, 11, 12], "customer_id": [1, 1, 3]})

# works on pandas 2.x and 3.0
tagged = customers.merge(orders, on="customer_id", how="left", indicator=True)
no_orders = tagged.loc[tagged["_merge"] == "left_only", ["customer_id", "name"]]
print(no_orders)  # customers 2 and 4

# pandas 3.0 only
anti = customers.merge(orders, on="customer_id", how="left_anti")
print(anti[["customer_id", "name"]])  # customers 2 and 4

go deeper

for a junior

Remember indicator=True and its three values, and that the anti-join is the left_only rows of a left merge.

for a middle

Explain why repeated orders do not duplicate unmatched customers, how outer plus indicator reconciles both sides, and what pandas 3.0's left_anti replaces.

for a senior

Watch for null keys matching each other, multi-column keys, and code that must still run on 2.x before reaching for how='left_anti'.

for a principal

Decide whether a team's reconciliation checks standardise on outer merges with indicator, so orphan rows on either side are reported every run.

## The question behind the question An **anti-join** keeps the rows of one table whose key has **no** match in another: customers with no orders, products never sold, accounts missing from a reconciliation file. The idea is library-neutral; what an interviewer checks here is which pandas arguments express it and what the result looks like. ## The indicator pattern (works in every supported release) `merge` takes `indicator=True`, which adds a column called `_merge` to the result: | `_merge` value | Meaning | |---|---| | `left_only` | the row's key appears only in the left frame | | `right_only` | the row's key appears only in the right frame | | `both` | the key was found in both frames | The column has a **categorical** dtype with those three categories, whichever `how` you used. The recipe: 1. Merge with `how="left"` so every customer survives: `customers.merge(orders, on="customer_id", how="left", indicator=True)`. 2. Filter `tagged["_merge"] == "left_only"`. 3. Keep only the customer columns: the order columns are all missing on those rows. Details that matter: - A customer with three orders appears **three times** in the merged frame, but customers with no order appear exactly once, so the filtered result has one row per unmatched customer as long as the customer table itself has unique keys. - Pass a string instead of `True` (`indicator="source"`) to name the column differently. - If either frame already has a column called `_merge`, pandas raises `ValueError` rather than overwriting it; a string name avoids the clash. - With `how="outer"`, the same column shows both directions: `left_only` rows are customers without orders, `right_only` rows are orders whose `customer_id` has no customer, a referential-integrity check in one pass. ## `how="left_anti"` and `how="right_anti"` in pandas 3.0 pandas 3.0 added two values to `how` for `pd.merge`, `DataFrame.merge` and `DataFrame.join`: - `"left_anti"`: keep left rows whose key is not in the right frame, preserving key order; - `"right_anti"`: keep right rows whose key is not in the left frame. So `customers.merge(orders, on="customer_id", how="left_anti")` replaces merge, filter and drop. The right frame's non-key columns still come back as columns, empty on every row, so select the customer columns afterwards. Code that has to run on pandas 2.x must keep the indicator pattern, because 2.x has no anti-join value for `how`. ## What the merged frame looks like Reading the intermediate result is part of the answer: - The left merge returns **one row per customer-order pair**, plus one row per customer without orders; its index is a fresh default index, because merging columns on columns discards both input indexes. - On `left_only` rows every column that came from `orders` is missing. An integer column such as `order_id` therefore comes back as `float64`, since NumPy integers cannot hold `NaN`; in pandas 3.0 a text column keeps the `str` dtype with `NaN` as its missing value. - The `_merge` column sits at the end of the frame, after the columns of both inputs. Selecting the customer columns with `.loc[mask, ["customer_id", "name"]]` in the same step keeps those artefacts out of the result. ## Other spellings and why the merge versions win - A boolean mask such as `~customers["customer_id"].isin(orders["customer_id"])` also finds unmatched customers on a single key. It is short, but it only handles one key column; the boolean-mask lesson covers it in depth. - The indicator approach handles **multi-column keys** (`on=["customer_id", "region"]`), keeps the full right-hand context for `both` rows, and lets one call answer both directions with `how="outer"`. ## Pitfalls interviewers probe - **Missing keys.** pandas matches null keys against each other when both key columns contain them, unlike SQL. A customer with a missing `customer_id` can therefore show up as `both` if any order also lacks a key. Clean or drop null keys first. - **Key dtypes.** An integer `customer_id` on one side and a string one on the other does not quietly match nothing: `merge` raises `ValueError` asking you to fix the types. Keys that differ in whitespace or case, by contrast, match nothing silently, which the library-neutral material on near-matching keys covers. - **Counting the result.** `tagged["_merge"].value_counts()` is a quick reconciliation summary; on the left merge it shows `left_only` and `both`, and `right_only` with a zero count, because the column is categorical.

  • How would you find orders that reference a customer_id missing from the customer table, in the same pass?
    Merge with `how="outer"` and `indicator=True`. Rows tagged `left_only` are customers without orders, rows tagged `right_only` are orders whose key has no customer, and `both` rows matched. In pandas 3.0 you can instead run `orders.merge(customers, on="customer_id", how="left_anti")` for the orphan orders alone.
  • Why can a customer with a missing customer_id appear as 'both' in the indicator column?
    pandas matches null keys with each other when both key columns contain them, which differs from SQL, where NULL never equals NULL. If any order also has a missing `customer_id`, the keyless customer pairs with it and is tagged `both`. Drop or fill null keys before the merge.
  • Why is the _merge column categorical, and what does that change when you count it?
    pandas builds it as a `Categorical` with the fixed categories `left_only`, `right_only` and `both`. `value_counts()` therefore lists all three categories, showing zero for one that never occurs, which makes it a stable reconciliation summary across runs.

  • Filters _merge == 'right_only' to find customers without orders after customers.merge(orders).
  • Uses an inner merge and expects unmatched customers to appear with missing values.
  • Believes pandas never matches missing keys, as SQL does with NULL.
  • Claims how='left_anti' works on pandas 2.x.
  • Thinks the anti-join result drops the right frame's columns automatically.

Assumes pandas 3.0, where merge and join accept how='left_anti' and 'right_anti'; pandas 2.x has no anti-join value and needs indicator=True plus a filter.