0
0
NumPydata~5 mins

Boolean indexing in NumPy

Choose your learning style9 modes available
Introduction
Boolean indexing helps you pick data from arrays by using True or False values. It makes finding and selecting data easy and fast.
You want to find all numbers greater than 10 in a list of numbers.
You need to select rows in a table where a condition is met, like ages over 18.
You want to filter out bad or missing data from your dataset.
You want to quickly find all items that match a rule without looping.
You want to change only certain values in an array based on a condition.
Syntax
NumPy
filtered_array = array[condition]

# where 'condition' is a boolean array of the same shape as 'array'
The condition inside the brackets must be a boolean array (True or False values).
The result is a new array with only the elements where the condition is True.
Examples
Selects all numbers greater than 5 from the array.
NumPy
import numpy as np
arr = np.array([1, 5, 10, 15])
result = arr[arr > 5]
Selects numbers divisible by 20 using a boolean mask.
NumPy
arr = np.array([10, 20, 30, 40])
mask = arr % 20 == 0
result = arr[mask]
Selects numbers greater than 2 and less than 5 using multiple conditions.
NumPy
arr = np.array([1, 2, 3, 4, 5])
result = arr[(arr > 2) & (arr < 5)]
Sample Program
This program filters the ages array to find all people who are 18 or older using boolean indexing.
NumPy
import numpy as np

# Create an array of ages
ages = np.array([12, 17, 19, 24, 15, 30])

# Select ages 18 or older
adults = ages[ages >= 18]

print("Original ages:", ages)
print("Adults (18 or older):", adults)
OutputSuccess
Important Notes
Boolean indexing does not change the original array unless you assign back to it.
You can combine multiple conditions using & (and), | (or), and ~ (not) with parentheses.
Boolean indexing works with multi-dimensional arrays too, selecting elements where the condition is True.
Summary
Boolean indexing uses True/False arrays to pick data from numpy arrays.
It is a fast and easy way to filter or select data based on conditions.
You can combine multiple conditions to select exactly what you want.