How do I create a boolean mask in NumPy?

95 views

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
0

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 > 3 creates a boolean array where each element is True if the condition is met and False otherwise.
  • Applying the mask to arr returns only the elements where the condition is True.
solveurit24@gmail.com Changed status to publish February 13, 2025
0