HOW TO FILTER PYTHON NUMPY ARRAYS?

We can filter an array using boolean index list, which 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.

import numpy as np

arr = np.array([1, 2, 3, 4])

booleanlist = [True, False, True, False]

filteredarray = arr[booleanlist]

print(filteredarray)

Output-

[1 3]

The new array contains only the values where the filter array had the value True, in this case, index 0 and 2

Creating the filter array

import numpy as np

arr = np.array([1, 2, 3, 4])
filter_arr = arr > 2

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

Output-

[False False  True  True]
[3 4]

Posted

in

Tags:

Comments

Leave a Reply