Sunday, May 31, 2020

Numpy filter array

Numpy Filter array


Filtering Arrays 


Filtering items form an array and generating a new array out of them is called filtering. We can filter an array using a boolean index list in a Numpy ndarray. A boolean index list is a list of booleans corresponding to indexes in the array. The values corresponding to True are included and the values corresponding to the False are excluded from the resultant array.

import numpy as np
nums = np.array([10, 20, 30, 40, 50])
f = [True, False, True, False, True]
result = nums[f]
print(result)

#Output
[10 30 50]

Creating and using a Filter array


It can be time-consuming and complex to create a hard-coded filter array, but we can create and populate a filter array programmatically.

For 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 % 20 == 0:
    filter_nums.append(True)
  else:
    filter_nums.append(False)

result=nums[filter_nums]

print(filter_nums)
print(result)

#output
[False, True, False, True, False, True, False, True, False]
[20 40 60 80]

OR

import numpy as np

nums = np.array([10, 20, 30, 40 , 50, 60, 70, 80, 90])
filter_arr = (nums%20 == 0)
newarr = nums[filter_arr]

print(filter_arr)
print(newarr)

#Output
[False  True False  True False  True False  True False]
[20 40 60 80]


Creating a filter array for 2-D array


import numpy as np

nums = np.array([[10, 20, 30],[40 , 50, 60], [70, 80, 90]])
filter_arr = (nums%20 == 0)
newarr = nums[filter_arr]

print(filter_arr)
print(newarr)

#Output
[[False  True False]
 [ True False  True]
 [False  True False]]
[20 40 60 80]