Last updated

Searching & Filtering

Definition: A boolean mask is an array of True/False values used to pick out elements that meet a condition — one of the most powerful features of NumPy.

Example 1 — filter with a condition

import numpy as np
a = np.array([10, 25, 30, 45, 50])
print(a > 30)        # [False False False True True]
print(a[a > 30])     # [45 50]  -> only matching values

Writing a[a > 30] reads as "give me the elements of a where a is greater than 30".

Example 2 — find positions with where

import numpy as np
a = np.array([10, 25, 30, 45, 50])
print(np.where(a > 30))   # indices: (array([3, 4]),)

Example 3 — replace based on a condition

import numpy as np
a = np.array([10, 25, 30, 45, 50])
print(np.where(a > 30, "big", "small"))

💡 Tip: boolean masks replace slow loops. Combine conditions with & (and) and | (or), each part in brackets: a[(a > 20) & (a < 50)].

Try it Yourself
Output

          
Ad · responsive