How to filter arrays in NumPy

How to filter arrays in NumPy
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.
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.
Example
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
How to filter arrays in NumPy
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
How to filter arrays in NumPyCreating a filter array for a 2-D array
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 
How to filter arrays in NumPy
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.
Ask Question #trycoder

Facebook Page👉 https://bit.ly/3o688OF
Watch more videos here
Click to SUBSCRIBE to more Videos!

Please Like, Comment, Share and Subscribe THANK YOU!

0 Comments