LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Python Data Science NumPy Filter Array
Filtering Arrays
Filtering refers to getting some elements out of an existing array and creating a new array out of them.
In NumPy, an array is filtered using a boolean index list.
A boolean index list is a list of booleans corresponding to indexes in the array.
If the value at an index is True that element is contained in the filtered array, if the value at that index is False that element is excluded from the filtered array.
Example 1: Create an array from the elements on index 0 and 2.
Code
the output will be
[11 13]
The example above returns [11, 13], why?
Because the new filter contains only the values where the filter array had the value True, in this case, index 0 and 2.
Creating the Filter Array
In the example above we hard-coded the True and False values, but the common use is to create a filter array based on conditions.
Example 2: Create a filter array that will return only values higher than 12.
Code
the output will be
[False, False, True, True]
[13 14]
Example 3: Create a filter array that will return only even elements from the original array.
Code
the output will be
[False, True, False, True, False, True, False]
[12 14 16]
Creating Filter Directly From Array
NumPy provides a nice way to tackle the above task which is quite a common task in NumPy.
We can directly substitute the array instead of the iterable variable in our condition and it will work just as we expect it to.
Example 4: Create a filter array that will return only values higher than 12.
Code
import numpy as np
arr = np.array([11, 12, 13, 14])
filter_arr = arr > 12
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)
the output will be
[False False True True]
[13 14]
Example 5: Create a filter array that will return only even elements from the original array.
Code
import numpy as np
arr = np.array([11, 12, 13, 14, 15, 16, 17])
filter_arr = arr % 2 == 0
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)
the output will be
[False True False True False True False]
[12 14 16]