Skip to main content

Introduction to Python NumPy Filter Array

Python NumPy Filter Array

In NumPy, you can filter an array to extract only the elements that meet a specific condition using a Boolean mask.

A Boolean mask is an array of the same shape as the original array, where each element is either True or False based on the condition.

Here's an example of filtering an array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

# Create a Boolean mask based on a condition
mask = arr > 2

# Apply the mask to the original array
filtered_arr = arr[mask]

print(filtered_arr) # Output: [3 4 5]

In this example:

  • We create a Boolean mask mask based on the condition arr > 2, which checks if each element of arr is greater than 2.
  • The resulting mask is [False, False, True, True, True].
  • Then, we apply the mask to the original array arr by indexing it with the mask arr[mask], which gives us the filtered array containing only the elements that satisfy the condition.

You can also directly use the condition as an index to filter the array without explicitly creating a mask:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

# Filter the array based on a condition
filtered_arr = arr[arr > 2]

print(filtered_arr) # Output: [3 4 5]

This approach achieves the same result as the previous example but avoids the explicit creation of the Boolean mask.