Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

NumPy Array Filter

Filtering Arrays

Extracting certain elements from an existing array to create a new array is known as filtering.

In NumPy, you can filter an array using a boolean index list.

A boolean index list is a collection of boolean values that correspond to the indices in the array.

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

Example

Generate an array using the elements at indices 0 and 2:

import numpy as np

arr = np.array([41424344])

x = [TrueFalseTrueFalse]

newarr = arr[x]

print(newarr)

The example above will return [41, 43]. Why?

 

Because the new array includes only the values where the filter array has a value of True, which corresponds to indices 0 and 2.

Creating the Filter Array

In the example above, we manually specified the True and False values; however, it is more common to generate a filter array based on specific conditions.

Example

Generate a filter array that returns only the values greater than 42:

import numpy as np

arr = np.array([41424344])

# Create an empty list
filter_arr = []

# go through each element in arr
for element in arr:
  # if the element is higher than 42, set the value to True, otherwise False:
  if element > 42:
    filter_arr.append(True)
  else:
    filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

Example

Generate a filter array that will return only the even elements from the original array:

import numpy as np

arr = np.array([1234567])

# Create an empty list
filter_arr = []

# go through each element in arr
for element in arr:
  # if the element is completely divisble by 2, set the value to True, otherwise False
  if element % 2 == 0:
    filter_arr.append(True)
  else:
    filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)