NumPy Array Filtering

Array Filtering

Taking some elements from an existing array to create a new array is called filtering (filtering).

In NumPy, we use boolean index lists to filter arrays.

Boolean index lists are lists of boolean values corresponding to the indices in the array.

if the value at the index is Truethen the element will be included in the filtered array; if the value at the index is Falsethen the element will be excluded from the filtered array.

Example

Create an array using the elements at indices 0 and 2, 4:

import numpy as np
arr = np.array([61, 62, 63, 64, 65])
x = [True, False, True, False, True]
newarr = arr[x]
print(newarr)

Run Instance

The example will return [61, 63, 65]Why?

Because the new filter only contains the elements with values in the filter array True so in this case, the indices are 0 and 2, 4.

create a filter array

In the example above, we create the value of True and False The value is hard-coded, but the usual use is to create a filter array based on conditions.

Example

Create a filter array that returns only values greater than 62:

import numpy as np
arr = np.array([61, 62, 63, 64, 65])
# Create an empty list
filter_arr = []
#
# Traverse each element in arr
  # If the element is greater than 62, set the value to True, otherwise to False:
  if element > 62:
    filter_arr.append(True)
  else:
    filter_arr.append(False)
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)

Run Instance

Example

Create a filter array that returns only even elements from the original array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
# Create an empty list
filter_arr = []
#
# Traverse each element in arr
  # If the element can be divided by 2, set the value to True, otherwise set it to False
  if element % 2 == 0:
    filter_arr.append(True)
  else:
    filter_arr.append(False)
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)

Run Instance

Create a filter directly from the array

The previous example is a very common task in NumPy, and NumPy provides a good method to solve this problem.

We can directly replace the array in the condition instead of the iterable variable, and it will work as expected.

Example

Create a filter array that returns only values greater than 62:

import numpy as np
arr = np.array([61, 62, 63, 64, 65])
filter_arr = arr > 62
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)

Run Instance

Example

Create a filter array that returns only even elements from the original array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
filter_arr = arr % 2 == 0
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)

Run Instance