isin() and between() Filters
Select rows where a column value is in a list with isin() or within a numeric range with between().
The isin() Method Overview
isin() checks whether each element of a Series is contained in a given list (or set) of values. It returns a boolean Series that you can use directly for row filtering. This is more concise and often faster than chaining multiple == comparisons with |.
For example, instead of (df['country'] == 'USA') | (df['country'] == 'UK'), you write df['country'].isin(['USA', 'UK']).
import pandas as pd
df = pd.DataFrame({
'country': ['USA', 'Germany', 'UK', 'France', 'USA'],
'sales': [400, 200, 150, 300, 600]
})
# Check membership
mask = df['country'].isin(['USA', 'UK'])
print(mask.tolist()) # [True, False, True, False, True]
result = df[mask]
print(result)
# country sales
# 0 USA 400
# 2 UK 150
# 4 USA 600isin() with Sets for Speed
You can pass a Python set instead of a list to isin(). Membership look-up in a set is O(1) — it doesn't get slower as the list grows. This matters when your allowed values list has thousands of entries, making set-based isin() significantly faster than list-based isin().
import pandas as pd
df = pd.DataFrame({
'sku': ['A001', 'B002', 'A003', 'C004', 'B005'],
'qty': [10, 5, 3, 8, 12]
})
# Use a set for fast membership check
allowed_skus = {'A001', 'A003', 'B005'}
result = df[df['sku'].isin(allowed_skus)]
print(result)
# sku qty
# 0 A001 10
# 2 A003 3
# 4 B005 12All lessons in this course
- Boolean Indexing on DataFrames
- The query() Method
- isin() and between() Filters
- Selecting Columns by Pattern