Boolean Indexing / Mask (Pandas)

Boolean indexing filters a DataFrame or Series by passing it an array of True/False values, keeping only the rows where the condition is True. The boolean array is called a mask.

Pandas

You build a mask by writing a comparison on a column — df['age'] > 30 — which returns a boolean Series the same length as the frame. Feeding that mask back in with df[mask] keeps only the matching rows. This is the most common way to filter data in pandas.

Combine conditions with the bitwise operators & (and), | (or), and ~ (not), and wrap each condition in parentheses because those operators bind tighter than comparisons. Do not use the Python keywords and/or here — they raise an error on arrays.

Masks also work for assignment: df.loc[df['x'] < 0, 'x'] = 0 clamps negatives to zero. For long or readable conditions, query() can express the same filter as a string.

Syntax

df[df['col'] > value]  |  df[(cond1) & (cond2)]

Examples

Python

import pandas as pd
s = pd.Series([1, 2, 3, 4])
print(s[s > 2])

Output:

2    3
3    4
dtype: int64

Learn it in a lesson

See also

Back to the Dictionary