Boolean Masks and Indexing in NumPy
NumPy allows for powerful data manipulation using boolean masks and indexing, which help in filtering and modifying arrays efficiently.
1. Importing NumPy
Before using boolean masks and indexing, import NumPy.
import numpy as np
2. Creating Boolean Masks
A boolean mask is an array of boolean values (True
or False
) used to filter elements.
arr = np.array([10, 20, 30, 40, 50]) mask = arr > 25 print(mask) # Output: [False False True True True]
3. Applying Boolean Masks
Use a boolean mask to extract elements that meet a condition.
filtered_arr = arr[arr > 25] print(filtered_arr) # Output: [30 40 50]
4. Combining Conditions
Use logical operators (&
for AND, |
for OR) to combine conditions.
mask = (arr > 15) & (arr < 45) print(arr[mask]) # Output: [20 30 40]
5. Modifying Elements Using Boolean Masks
Boolean masks can also be used to modify array elements.
arr[arr > 25] = 99 print(arr) # Output: [10 20 99 99 99]
6. Conclusion
Boolean masks and indexing in NumPy provide an efficient way to filter, modify, and manipulate data.