How do I create a boolean mask in NumPy?
How do I create a boolean mask in NumPy?
How do I create a boolean mask in NumPy?
solveurit24@gmail.com Changed status to publish February 13, 2025
A boolean mask allows you to filter elements in a NumPy array based on a condition. Here’s how to create one:
import numpy as np
# Create an array
arr = np.array([1, 2, 3, 4, 5])
# Create a boolean mask for elements greater than 3
mask = arr > 3
print(mask) # Output: [False False False True True]
# Apply the mask to filter elements
filtered = arr[mask]
print(filtered) # Output: [4 5]
Explanation:
- The condition
arr > 3creates a boolean array where each element isTrueif the condition is met andFalseotherwise. - Applying the mask to
arrreturns only the elements where the condition isTrue.
solveurit24@gmail.com Changed status to publish February 13, 2025