← Back to NumPy Course | Chapter 4: Indexing & Slicing | Lesson 6 of 7

Boolean indexing

Filter an array by a true/false condition to keep only the values you want.

In this page:

  1. Boolean indexing
Syntax
python
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

python
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
  1. Using and / or instead of & / |
  2. Forgetting parentheses around each condition
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.