Filter a NumPy Array
Boolean indexing selects array elements whose corresponding condition evaluates to true.
What is Filter a NumPy Array?
Boolean indexing selects array elements whose corresponding condition evaluates to true.
Filter NumPy values with boolean indexing.
When should you use it?
- Perform numerical operations on many values at once.
- Process arrays, matrices, and scientific data efficiently.
- Prepare data for data science and machine learning.
Example code
main.py
import numpy as np
scores = np.array([64, 82, 91, 73, 88])
passing = scores[scores >= 80]
print(passing)
Expected output
[82 91 88]
How it works
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.