numpy Boolean indexing


Example

arr = np.arange(7)
print(arr)
# Out: array([0, 1, 2, 3, 4, 5, 6])

Comparison with a scalar returns a boolean array:

arr > 4
# Out: array([False, False, False, False, False,  True,  True], dtype=bool)

This array can be used in indexing to select only the numbers greater than 4:

arr[arr>4]
# Out: array([5, 6])

Boolean indexing can be used between different arrays (e.g. related parallel arrays):

# Two related arrays of same length, i.e. parallel arrays
idxs = np.arange(10)
sqrs = idxs**2

# Retrieve elements from one array using a condition on the other
my_sqrs = sqrs[idxs % 2 == 0]
print(my_sqrs)
# Out: array([0, 4, 16, 36, 64])