Hello. Welcome to this session on this platform on NumPy module. If you are new here please do checkout our previous articles on NumPy. Also do checkout our YouTube channel to get a better understanding of this article. Example
In this article we are going to see how to filter arrays in NumPy
What is filtering?
Filtering elements in an array means removing elements from an existing array and creating a new array out of them. This filtering is usually done using a Boolean index list. This Booleans index correspond to the indexes in the given array.
After the compiler execute the program and the value corresponding to the index is found to be true, the value is included and if found false, the value is excluded from the output.
import numpy as np
nums = np.array([10, 20, 30, 40, 50])
f = [True, False, True, False, True]
result = nums[f]
print(result)
The compiler runs the program and find the Booleans corresponding the values as true. These values are returned as the output.
OUTPUT
Creating and using filter array
In addition to the example we saw above, In NumPy we can use conditions to create filter array programmatically.
Example
import numpy as np
nums = np.array([10, 20, 30, 40 , 50, 60, 70, 80, 90])
# Create an empty list
filter_nums = []
# go through each element in array
for item in nums:
# if the element is divisible by 20,
# set the value to True, otherwise False
if item % 30 == 0:
filter_nums.append(True)
else:
filter_nums.append(False)
result=nums[filter_nums]
print(filter_nums)
print(result)
When the compiler executes the program written above, values which are divisible by 30 filtered out and the Booleans indexes corresponding to these values are returned as true and false if otherwise
OUTPUT
In this case we are going to use the filter array directly to simultaneously filter out a set of given arrays.
Example
import numpy as np
nums = np.array([[10, 20, 30],[40 , 50, 60], [70, 80, 90]])
filter_arr = (nums%30 == 0)
newarr = nums[filter_arr]
print(filter_arr)
print(newarr)
Above, the compilers filter values which are divisible by 30 in the given set of arrays and returns the output as a Boolean list of the given arrays and the values which are divisible by 30
OUTPUT
We have seen how to create a new array from an existing array. Hope this article was well understood and in case of any question, you can leave the question at the comment section. Happy learning guys.
Comments
Post a Comment
Please do not enter any spam link in the comment box.