The previous example represents a common task in NumPy, which provides an efficient way to handle it.
We can directly use the array in place of the iterable variable in our condition, and it will function as expected.
Generate a filter array that returns only the values greater than 42:
import numpy as np arr = np.array([41, 42, 43, 44]) filter_arr = arr > 42 newarr = arr[filter_arr] print(filter_arr) print(newarr) |
Generate a filter array that returns only the 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) |