A boolean array of the same shape (or broadcastable) selects elements where True. This is the idiomatic way to filter ndarrays.
Mask filtering
import numpy as np
a = np.array([1, -2, 3, -4, 5])
pos = a[a > 0]
print(pos)
Compound conditions
Combine with & (and), | (or), ~ (not)—each condition must be parenthesized: (a > 0) & (a < 10).
Assignment via mask
import numpy as np
a = np.array([1, 2, 3, 4, 5])
a[a % 2 == 0] = 0
print(a)
Important interview questions and answers
- Q: Why not use and/or keywords?
A: Pythonand/ordon't element-wise broadcast on arrays. - Q: Boolean indexing copy?
A: Returns a copy—assigning through mask modifies original in place.
Self-check
- Select elements between 2 and 8 inclusive.
- Set negative values to zero using a mask.
Pitfall: Use & and |, not Python and/or.
Interview prep
- and vs &?
Use & | ~ with parentheses for element-wise boolean arrays.
- Filter pattern?
arr[mask] selects True positions.