Boolean indexing helps you pick only the data you want from a big list or table. It makes finding and using specific data easy and fast.
0
0
Boolean indexing for filtering in NumPy
Introduction
You want to find all temperatures above 30 degrees in a weather dataset.
You need to select only the students who passed an exam from a list of scores.
You want to filter out all negative numbers from a list of measurements.
You want to get all sales records where the amount is greater than 1000.
You want to find all rows in a table where a condition is true, like customers from a certain city.
Syntax
NumPy
filtered_array = array[condition]
The condition is a Boolean array or expression that is the same shape as array.
Only elements where condition is True are kept in filtered_array.
Examples
This keeps only numbers greater than 25 from the array.
NumPy
import numpy as np arr = np.array([10, 20, 30, 40, 50]) filtered = arr[arr > 25]
This keeps numbers between 15 and 35 inclusive.
NumPy
arr = np.array([5, 15, 25, 35, 45]) filtered = arr[(arr >= 15) & (arr <= 35)]
This keeps only even numbers from the array.
NumPy
arr = np.array([1, 2, 3, 4, 5]) filtered = arr[arr % 2 == 0]
Sample Program
This program creates a list of ages and then uses Boolean indexing to select only those 18 or older. It prints both the full list and the filtered list.
NumPy
import numpy as np # Create an array of ages ages = np.array([12, 17, 24, 35, 42, 15, 19]) # Filter ages to get only adults (18 and older) adults = ages[ages >= 18] print("All ages:", ages) print("Adults only:", adults)
OutputSuccess
Important Notes
Boolean indexing works with arrays of any shape, not just 1D.
Make sure the condition array matches the shape of the original array.
You can combine multiple conditions using & (and), | (or), but use parentheses around each condition.
Summary
Boolean indexing lets you pick data by True/False conditions.
It is a fast and simple way to filter arrays in numpy.
Use logical operators to combine multiple conditions.