Write Python. Understand every error.

Starting Python in your browser…

NumPy · topic 22 of 25

Boolean masks and filtering

Comparing an array with a value gives an array of True and False, one for each element. This is called a boolean mask.

a = np.array([12, 45, 7, 60])
print(a > 20)       # [False  True False  True]
print(a[a > 20])    # [45 60]

Putting a mask inside square brackets keeps only the elements where the mask is True. This replaces a loop with an if inside it.

To combine conditions, use & for "and", | for "or" and ~ for "not", and put brackets around each condition: a[(a > 10) & (a < 50)]. The words and and or do not work on arrays and cause an error.

Because True counts as 1, mask.sum() or np.count_nonzero(mask) counts matching elements, and mask.mean() gives the fraction that match.

np.where(condition, x, y) builds a new array, taking x where the condition holds and y elsewhere. A mask can also be used on the left of = to change only some elements: a[a < 0] = 0.

Key takeaways

  • Comparing an array with a value gives an array of True and False, called a boolean mask.
  • Putting a mask inside square brackets keeps only the elements where the mask is True.
  • Combine conditions with &, | and ~, and put brackets around each condition.
  • mask.sum() counts the matches, and np.where(condition, x, y) chooses between two values.

Common mistakes

  • Using and or or on arrays instead of & and |. Read the ValueError guide.
  • Leaving out the brackets around each condition. Write (a > 2) & (a < 8); without brackets the operators run in a different order and the result is wrong or an error.
  • Expecting the mask itself to hold the values. It only says which positions to keep.

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.