Boolean indexing
Filter an array by a true/false condition to keep only the values you want.
In this page:
Syntax
mask = arr > value
arr[mask]
arr[(arr > a) & (arr < b)]
Boolean indexing
A comparison such as arr > 3 gives a boolean array of the same shape. Using that mask as an index returns only the True elements. Combine conditions with & and | wrapped in parentheses.
Note:
Boolean indexing always returns a copy, unlike slicing.
Example: Boolean indexing
import numpy as np
a = np.array([1, 5, 8, 3, 10, 2])
mask = a > 4
print(mask)
print(a[mask])
print(a[(a > 2) & (a < 9)])
a[a > 8] = 0
print(a)
# Output:
# [False True True False True False]
# [ 5 8 10]
# [5 8 3]
# [1 5 8 3 0 2]
Related Topics
Common Mistakes
- Using and / or instead of & / |
- Forgetting parentheses around each condition
- Expecting a view to be returned
Chapter Summary
- Comparisons produce boolean masks
- Masks select matching elements
- Combine with & | ~
- Result is a copy
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: