Filtering NumPy Array
In this tutorial you will learn:
- What is Array Filtering?
- Boolean Array based filtering
Array Filtering
Separating specific elements based on a specific condition and making another array from those elements is called filtering. Filtering can be carried out either by iterating complete array and checking each element against a specific condition or it can be carried out using by applying a Boolean array on the given array which we want to filter out.
Boolean Array Based Filtering
In NumPy, Boolean Array filtration is carried out using a Boolean index list, when the index is found “True”, that specific element will be added into the filtered array.
Lets take an example to further comprehend the process of Boolean array filtering. In this example you can observe that we have filtered any array by using a hard coded Boolean index array having Boolean elements “True” and “False”, so only those values will be filtered out which are having “True” at their respective index. In the third line of code we are declaring an array with 4 integer values, in the sixth line of code we are declaring the Boolean filter array and in tenth line we are applying the Boolean filter to the array which was declared in third line of the code. In results you can observe that only those elements are filtered out, which are having “True” at their respective index.
- import numpy as np
- #declaring an array to be filtered
- my_arr = np.array([1, 2, 3, 4])
- #printing the array which is to be filtered
- print('Array to be filtered:\n',my_arr)
- #declaring a boolean index list
- bin_arr = [False,True, False, True]
- #prinitng boolean index list
- print('Boolean index list which will be applied to filter the array:', bin_arr)
- #applying boolean index list to the array
- res = my_arr[bin_arr]
- #printing the filtered array
- print('Result after Array filtration: ', res)
Lets take another example, in this example we will be filtering an array of string using a boolean array. It must be kept in mind that the array being filtered and the Boolean index list must have the same number of elements, otherwise the compiler will give an error that the Boolean index did not match.
- import numpy as np
- #declaring an array to be filtered having data type string
- my_arr = np.array(['Source', 'Codester', 'Tutorials', 'Are','Fun','To','Learning'])
- #printing the String array which is to be filtered
- print('Array of DataType ''String'' to be filtered:\n',my_arr)
- #declaring a boolean index list
- bin_arr = [True,True, False, False,True,False,True]
- #prinitng boolean index list
- print('Boolean index list which will be applied to filter the array:', bin_arr)
- #applying boolean index list to the array
- res = my_arr[bin_arr]
- #printing the filtered array
- print('Result after Array filtration: ', res)
Add new comment
- 78 views