English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Filtering an array from an existing array to create a new array is called 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.
Using index 0 and 2,4 Create an array from the elements on
import numpy as np arr = np.array([61, 62, 63, 64, 65)] x = [True, False, True, False, True] newarr = arr[x] print(newarr)
Running Result:
[61 63 65]
The example will return [61, 63, 65]Why?
Because the new filter only contains the values in the filter array True The value, so in this case, the index is 0 and 2,4.
In the example above, we create a filter array for True and False The values are hard-coded, but the general usage is to create a filter array based on conditions.
Create a filter array that returns only elements greater than 62 value filter array:
import numpy as np arr = np.array([61, 62, 63, 64, 65)] # Create an empty list filter_arr = [] # Traverse each element in arr for element in arr: # If the element is greater than 62Then 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)
Running Result:
[False, False, True, True, True] [63 64 65]
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 for element in arr: # If the element can be 2 is divisible, 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)
Running Result:
[False, True, False, True, False, True, False] [2 4 6]
The 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.
Create a filter array that returns only elements greater than 62 value filter array:
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)
Running Result:
[False False True True True] [63 64 65]
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)
Running Result:
[False True False True False True False] [2 4 6]