Use df[df["col"].isin(values)] for a SQL WHERE col IN (...) filter and df[~df["col"].isin(values)] (with the bitwise negation operator ~) for a SQL WHERE col NOT IN (...) filter—or df.query("col in @values") / df.query("col not in @values") when chaining multiple filter conditions cleanly.
Basic Example
import pandas as pd
df = pd.DataFrame({
"order_id": [101, 102, 103, 104, 105],
"status": ["paid", "pending", "cancelled", "shipped", None],
"amount": [50.0, 20.0, 15.0, 90.0, 35.0],
})
allowed_statuses = {"paid", "shipped"}
# 1. SQL `WHERE status IN ('paid', 'shipped')`:
in_df = df[df["status"].isin(allowed_statuses)]
print(in_df)
# order_id status amount
# 0 101 paid 50.0
# 3 104 shipped 90.0
# 2. SQL `WHERE status NOT IN ('paid', 'shipped')`:
not_in_df = df[~df["status"].isin(allowed_statuses)]
print(not_in_df)
# order_id status amount
# 1 102 pending 20.0
# 2 103 cancelled 15.0
# 4 105 None 35.0
# 3. Method-chaining syntax with `df.query()` and `@` local variable injection:
chained_df = df.query("status not in @allowed_statuses and amount >= 20")
Key Details & Edge Cases
- Critical SQL difference on
NULL/NaNrows inNOT IN(~df["col"].isin(...)):- In SQL,
WHERE status NOT IN ('paid', 'shipped')evaluates toUNKNOWNforNULLrows and excludes them unless you writeOR status IS NULL. - In Pandas,
pd.Series([None, np.nan]).isin({"paid", "shipped"})returnsFalse, so negating with~df["status"].isin(...)keepsNaN/Nonerows! To match strict SQLNOT INbehavior (excluding nulls too), combine with.notna():strict_sql_not_in = df[~df["status"].isin(allowed_statuses) & df["status"].notna()]
- In SQL,
- Pass a
set(orlist/tuple/Series)—NEVER a bare string or scalar:- Passing a bare string (
df["status"].isin("paid")) raisesTypeError: only list-like objects are allowed to be passed to isin(), you passed astr``. Wrap single values in a list or set ({"paid"}), and prefer aset({"paid", "shipped"}) for $O(1)$ hash lookups when filtering against large lookup collections.
- Passing a bare string (
- Avoid Python’s
notkeyword (not df["col"].isin(...)fails):- Python’s
notcallsbool()on the entire Series and raisesValueError: The truth value of a Series is ambiguous. Always use the element-wise bitwise tilde operator~(~df["col"].isin(...)), and wrap multiple conditions in parentheses:df[(~df["status"].isin(allowed)) & (df["amount"] > 25)].
- Python’s
- Multi-column tuple membership (
WHERE (a, b) IN ((1, 'x'), (2, 'y'))):.isin()works on a singleSeriesor column-wise on aDataFrame(matching values per column independently, not row-wise tuples!). For exact multi-column(col_a, col_b)pair matching, convert columns to aMultiIndexor merge:pairs = {("paid", 50.0), ("shipped", 90.0)} mask = pd.MultiIndex.from_frame(df[["status", "amount"]]).isin(pairs) matched = df[mask]
Comparison of SQL-Like IN / NOT IN Filtering Methods in Pandas
| Pattern | SQL Equivalent | Keeps NaN / None Rows on NOT IN? |
Multi-Column Tuple Support? | Best Used When |
|---|---|---|---|---|
df[df["col"].isin(vals)] (Recommended) |
WHERE col IN (...) |
N/A (False unless np.nan in vals) |
Single column | Standard, fast vectorized membership filtering on any column. |
df[~df["col"].isin(vals)] (Recommended) |
WHERE col NOT IN (...) OR col IS NULL |
Yes (add & df["col"].notna() to drop nulls) |
Single column | Excluding a blocklist of categories, IDs, or statuses. |
df.query("col in @vals") / "not in @vals" |
WHERE col [NOT] IN (...) |
Yes | Single column | Readable multi-condition filters inside .pipe() / method chains. |
pd.MultiIndex.from_frame(df[cols]).isin(pairs) |
WHERE (c1, c2) IN ((...), (...)) |
Yes (on ~mask) |
Yes (exact row tuples) | Filtering rows by composite keys ((country, city) or (user_id, date)). |
You must log in or register to comment.
