Membership-based filtering
Filter rows whose selected column contains one of several permitted values.
Pandas · Module
Returns a boolean DataFrame indicating whether each cell's value is present in the supplied iterable, Series, DataFrame, or dictionary. Input type determines whether matching is global, column-specific, or label-aligned.
Call DataFrame.isin with a collection, mapping, Series, or DataFrame to produce a same-shaped boolean mask. Lists test every cell against shared values, dictionaries provide column-specific values, and labeled Series or DataFrames require matching labels for a true result.
DataFrame.isin(values)| Name | Type | Description |
|---|---|---|
values | iterable, Series, DataFrame or dict | Values to test against; may be an iterable, Series, DataFrame, or dictionary. Label matching rules depend on the input type. |
DataFrame of booleans showing whether each element in the DataFrame is contained in values.
~ for non-membership checks.import pandas as pd
df = pd.DataFrame(
{"num_legs": [2, 4], "num_wings": [2, 0]},
index=["falcon", "dog"],
)
mask = df.isin({"num_wings": [0, 3]})
print(mask)
print(df[mask["num_wings"]])Creates a boolean mask for allowed wing counts, then uses that mask to select matching rows.
Filter rows whose selected column contains one of several permitted values.
Apply different allowed-value sets to different columns.
Build a mask for values absent from a permitted set by negating the result.
DataFrame.isin return?It returns a boolean DataFrame with the same shape as the caller. Each cell indicates whether the corresponding value occurs in the supplied values structure.
Follow-up: How would you invert the membership test? Apply the bitwise ~ operator to the boolean DataFrame.
A list-like input is tested against every DataFrame element. A dictionary can specify separate candidate values for each column.
Follow-up: What must be true for a dictionary-based check? Its keys must match the DataFrame's column names.
For a Series input, the Series index must align with the DataFrame columns. For a DataFrame input, both index and column labels must match.
Follow-up: What happens when labels do not match? The corresponding membership results are not true because the documented label-matching condition is unmet.
DataFrameSeriesDataFrame.__invert__