Boolean Series
Comparing a Series gives True/False per item, and that mask can filter the Series.
In this page:
Syntax
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
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
- Using and / or instead of & / |
- Forgetting parentheses
- 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: