← Back to Pandas Course | Chapter 2: Series | Lesson 6 of 7

Boolean Series

Comparing a Series gives True/False per item, and that mask can filter the Series.

In this page:

  1. Boolean Series
Syntax
python
mask = s > value
s[mask]
s[(s > a) & (s < b)]

Boolean Series

A comparison such as s > 10 returns a boolean Series with the same index. Pass it inside brackets to keep only the True rows. Combine with & (and), | (or) and ~ (not), using parentheses.

Note: isin() tests membership in a list, and between() tests a range.

Example: Boolean Series

python
import pandas as pd

s = pd.Series([5, 12, 18, 3, 25])
mask = s > 10
print(mask)
print(s[mask])
print(s[s.between(4, 20)])

# Output:
# 0    False
# 1     True
# 2     True
# 3    False
# 4     True
# dtype: bool
# 1    12
# 2    18
# 4    25
# dtype: int64
# 0     5
# 1    12
# 2    18
# dtype: int64
Related Topics
Common Mistakes
  1. Using and / or instead of & / |
  2. Forgetting parentheses
  3. Confusing the mask with the filtered result
Chapter Summary
  • Comparisons yield boolean Series
  • Brackets with a mask filter
  • Use & | ~ with parentheses
  • isin and between are handy
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.