SoFunction
Updated on 2024-12-10

Array Filtering with NumPy for Python

Array Filtering

Taking some elements out of an existing array and creating a new one from it is called filtering.

In NumPy, we use Boolean indexed lists to filter arrays.

A Boolean indexed list is a list of Boolean values corresponding to the indexes in the array.

If the value at the index is True, the element is included in the filtered array; if the value at the index is False, the element is excluded from the filtered array.

an actual example

Creates an array with elements at indexes 0 and 2, 4:

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

running example

The above example will return [61, 63, 65], why?

Because the new filter only contains values for which the filter array has the value True, in this case the indexes are 0 and 2, 4.

Creating Filter Arrays

In the above example, we hard-coded the True and False values, but the usual use is to create filter arrays based on conditions.

an actual example

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

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

running example

an actual example

Creates a filter array that returns only the even elements of the original array:

import numpy as np
arr = ([1, 2, 3, 4, 5, 6, 7])
# Create an empty list
filter_arr = []
# Iterate over each element of arr
for element in arr:
  # Set the value to True if the element is divisible by 2, False otherwise
  if element % 2 == 0:
    filter_arr.append(True)
  else:
    filter_arr.append(False)
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)

running example

Creating filters directly from an array

The above example is a very common task in NumPy, and NumPy provides a good way to solve it.

Instead of iterable variables, we can just replace the array in the condition and it will work as we expect.

an actual example

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

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

running example

an actual example

Creates a filter array that returns only the even elements of the original array:

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

running example

This article on the use of Python's NumPy array filtering article is introduced to this, more related to NumPy array filtering content, please search for my previous posts or continue to browse the following articles hope that you will support me in the future!