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.
Generate an array using the elements at indices 0 and 2:
import numpy as np arr = np.array([41, 42, 43, 44]) x = [True, False, True, False] 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.
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.
Generate a filter array that returns only the values greater than 42:
import numpy as np arr = np.array([41, 42, 43, 44]) # 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) |
Generate a filter array that will return only the 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 = [] # 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) |