ZetCode

Pandas Boolean Indexing

last modified November 17, 2026 Python 3.15

Boolean indexing is the most common way to filter rows in Pandas. It keeps the rows where a condition is True and drops the rows where it is False. This article shows the basic mask, the comparison operators, and the helper methods that make conditions easier to write.

A boolean mask is a Series of True and False values with one entry per row. Pandas uses that mask as a filter: a row is returned only when its entry in the mask is True. Conditions can be stored in a variable and reused, which keeps more complex filters readable.

Filtering rows with a boolean mask

Comparing a column with a value produces a boolean Series. Passing that Series inside the square brackets of a DataFrame selects the matching rows. The original row labels are preserved in the result.

bool_mask.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'],
    'age': [25, 30, 35, 28, 33, 41],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin', 'Prague'],
    'salary': [1000, 1500, 2000, 1200, 1800, 2200]
}
df = pd.DataFrame(data)

mask = df['age'] > 30
print(mask)
print()
print(df[mask])

The condition df['age'] > 30 builds a mask with six True/False entries. Printing the mask shows which rows qualify; printing df[mask] shows those three rows in full. Using a named variable like mask is handy when the same condition is needed more than once.

$ python bool_mask.py
0    False
1    False
2     True
3    False
4     True
5     True
Name: age, dtype: bool

      name  age    city  salary
2  Charlie   35  London    2000
4      Eve   33  Berlin    1800
5    Frank   41  Prague    2200

Comparison operators

The usual Python comparison operators work on a whole column at once: == for equality, != for inequality, and <, <=, >, >= for ordering. Each operator returns a new boolean Series.

bool_compare.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'],
    'age': [25, 30, 35, 28, 33, 41],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin', 'Prague'],
    'salary': [1000, 1500, 2000, 1200, 1800, 2200]
}
df = pd.DataFrame(data)

print(df[df['city'] == 'Prague'])
print()
print(df[df['salary'] <= 1500])

The first filter keeps the two rows whose city is exactly Prague. The second keeps rows with a salary of 1500 or less. Notice that the condition is written directly inside the brackets; this is shorthand for creating a mask and then filtering with it.

$ python bool_compare.py
    name  age    city  salary
0  Alice   25  Prague    1000
5  Frank   41  Prague    2200

    name  age        city  salary
0  Alice   25      Prague    1000
1    Bob   30  Bratislava    1500
3  Diana   28       Paris    1200

Combining conditions with &, |, and ~

Real filters often combine several conditions. Pandas uses the bitwise operators & for AND, | for OR, and ~ for NOT. Because Python gives these operators a higher precedence than comparisons, each condition must be wrapped in parentheses. Without the parentheses the expression is parsed in a surprising way and fails.

bool_combine.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'],
    'age': [25, 30, 35, 28, 33, 41],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin', 'Prague'],
    'salary': [1000, 1500, 2000, 1200, 1800, 2200]
}
df = pd.DataFrame(data)

print(df[(df['age'] >= 30) & (df['salary'] > 1500)])
print()
print(df[(df['city'] == 'Prague') | (df['city'] == 'Berlin')])
print()
print(df[~(df['city'] == 'Prague')])

The first result keeps only rows that satisfy both conditions at once. The second keeps rows from either city. The third uses ~ to invert the mask, so it returns every row that is not from Prague. Each pair of parentheses produces one boolean Series before the operators combine them.

$ python bool_combine.py
      name  age    city  salary
2  Charlie   35  London    2000
4      Eve   33  Berlin    1800
5    Frank   41  Prague    2200

    name  age    city  salary
0  Alice   25  Prague    1000
4    Eve   33  Berlin    1800
5  Frank   41  Prague    2200

      name  age        city  salary
1      Bob   30  Bratislava    1500
2  Charlie   35      London    2000
3    Diana   28       Paris    1200
4      Eve   33      Berlin    1800

The isin method

When a column should match any value from a list, isin is shorter and clearer than chaining several == comparisons with |. It takes a list of accepted values and returns a boolean Series.

bool_isin.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'],
    'age': [25, 30, 35, 28, 33, 41],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin', 'Prague'],
    'salary': [1000, 1500, 2000, 1200, 1800, 2200]
}
df = pd.DataFrame(data)

print(df[df['city'].isin(['Prague', 'Berlin'])])

The expression df['city'].isin(['Prague', 'Berlin']) is True for every row whose city is one of the two listed values. The same idea works with numbers and with values from another Series.

$ python bool_isin.py
    name  age    city  salary
0  Alice   25  Prague    1000
4    Eve   33  Berlin    1800
5  Frank   41  Prague    2200

The between method

The between method tests whether a value lies inside a range. Unlike a Python slice, both ends of the range are inclusive, so a value equal to either boundary passes the test.

bool_between.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'],
    'age': [25, 30, 35, 28, 33, 41],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin', 'Prague'],
    'salary': [1000, 1500, 2000, 1200, 1800, 2200]
}
df = pd.DataFrame(data)

print(df[df['age'].between(28, 35)])

The filter keeps ages 28 through 35, including both 28 and 35. Writing the same condition by hand would require (df['age'] >= 28) & (df['age'] <= 35); between expresses it in one call.

$ python bool_between.py
      name  age        city  salary
1      Bob   30  Bratislava    1500
2  Charlie   35      London    2000
3    Diana   28       Paris    1200
4      Eve   33      Berlin    1800

The str.contains method

For text columns, str.contains tests whether each value contains a substring or matches a regular expression. Setting case=False makes the search case-insensitive, which is useful when the input is not consistently capitalised.

bool_contains.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'],
    'age': [25, 30, 35, 28, 33, 41],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin', 'Prague'],
    'salary': [1000, 1500, 2000, 1200, 1800, 2200]
}
df = pd.DataFrame(data)

print(df[df['name'].str.contains('a', case=False)])

Every name containing the letter "a" in either case is kept, so Alice matches because of its capital "A". The result is again a boolean Series used as a mask. More text tools are covered in the Pandas string methods tutorial.

$ python bool_contains.py
      name  age    city  salary
0    Alice   25  Prague    1000
2  Charlie   35  London    2000
3    Diana   28   Paris    1200
5    Frank   41  Prague    2200

Using query as an alternative

The query method accepts a condition as a single string instead of a boolean Series. Inside that string you refer to columns by name and you use the plain words and, or, and not. It is a readable alternative for longer filters.

bool_query.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'],
    'age': [25, 30, 35, 28, 33, 41],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin', 'Prague'],
    'salary': [1000, 1500, 2000, 1200, 1800, 2200]
}
df = pd.DataFrame(data)

print(df.query('age > 30 and salary > 1500'))

The string 'age > 30 and salary > 1500' produces the same rows as the parenthesised bitwise expression, but reads like a sentence. Note that query evaluates the string, so column names with spaces need backtick quoting.

$ python bool_query.py
      name  age    city  salary
2  Charlie   35  London    2000
4      Eve   33  Berlin    1800
5    Frank   41  Prague    2200

The &/| versus and/or precedence trap

The two ways of combining conditions cannot be mixed. In ordinary boolean indexing you must use & and | with parentheses; using the Python words and or or tries to reduce a whole Series to a single truth value and raises an error. Conversely, forgetting the parentheses lets & bind before the comparison, which raises an error as well. The example catches both errors.

bool_trap.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'],
    'age': [25, 30, 35, 28, 33, 41],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin', 'Prague'],
    'salary': [1000, 1500, 2000, 1200, 1800, 2200]
}
df = pd.DataFrame(data)

try:
    df[df['age'] > 30 and df['city'] == 'Prague']
except ValueError as e:
    print(type(e).__name__ + ':', e)

print()
try:
    df[df['age'] > 30 & df['city'] == 'Prague']
except TypeError as e:
    print(type(e).__name__ + ':', e)

The first error is ValueError because Python asks whether a Series as a whole is true, which is ambiguous. The second is TypeError because 30 & df['city'] is evaluated before the comparison. The fix is to write (df['age'] > 30) & (df['city'] == 'Prague'), or to move the whole condition into query, where and is correct.

$ python bool_trap.py
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.item(), a.any() or a.all().

TypeError: unsupported operand type(s) for &: 'int' and 'StringArray'

Source

Pandas Boolean Indexing Documentation

In this article we have filtered rows with boolean masks, compared columns with operators, combined conditions with &, | and ~, and used isin, between, str.contains and query. For selecting rows by integer position see Pandas iloc, and for working with text see Pandas string methods.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pandas tutorials.