Filter a NumPy Array with Boolean Indexing
Keep only the values you want with scores[scores >= 80], no loop needed.
- Building a boolean mask
- Indexing with the mask
- Combining conditions with & and |
A mask of True and False
The problem
Selecting the values you care about, such as passing scores, prices under a limit or temperatures above freezing, is one of the most common data tasks. With NumPy you do not need a loop: a condition picks the values for you.
Think of it like this
Boolean filtering is like holding a stencil over a row of numbers. The condition cuts a hole above every value that passes. Looking through the stencil, you see only those values.
scores >= 80✂️ Cut a hole above every passing score[False, True, True, False, True]🕳️ The stencil: holes where Truescores[scores >= 80]👀 Look through the holespassing📋 [82 91 88]Boolean indexing selects array elements with a mask of True and False values of the same shape, keeping the elements where the mask is True.
Key points
scores >= 80compares every element and returns an array of True and False.scores[scores >= 80]keeps only the elements where the mask is True.passingis a new array,[82 91 88];scoresis unchanged.- The order of the kept values is the same as in the original array.
When should you use it?
- Selecting values by a condition: outliers, valid readings, passing scores.
- Counting matches with
(scores >= 80).sum(). - Replacing values that match a condition.
When not to use it
- Ordinary Python lists: they do not support masks, so use a list comprehension.
- Labeled table data: pandas filtering keeps row labels and column names.
Example code
import numpy as np
scores = np.array([64, 82, 91, 73, 88])
passing = scores[scores >= 80]
print(passing)
Result of running the code
[82 91 88]
Code explanation
The comparison creates a boolean mask. Applying that mask to the original array returns only scores at or above 80.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input shape and dtype.
- Try negative, floating-point, and missing values.
- Apply the operation to larger multidimensional arrays and measure performance.
Common mistakes
Combining conditions with and
Python's and does not work on arrays; use & with parentheses.
scores[scores >= 80 and scores < 90]
scores[(scores >= 80) & (scores < 90)]
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Above-Average Values Keep the values that are greater than the average. Easy
- Count Positive Numbers Count the values greater than zero in a list. Easy