0

I know that I can use index expressions to filter a numpy array as shown in this SO answer.

>>> b = a[a>threshold]

But, what if I need the logical condition to be based on a field of the array to be filtered? e.g. with:

>>> arr = np.arange(12).reshape((3, 4))
>>> arr
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

When I try to do a similar filter based on the 3rd field/column:

>>> b = arr[arr[2]>0]

I get an error

Traceback (most recent call last):

File "", line 1, in

IndexError: boolean index did not match indexed array along dimension 0; dimension is 3 but corresponding boolean dimension is 4

I can't get the filtered array. What I need is the same result of the following list comprehension:

[r for r in aa if r[2] > 0]

with

aa =  [[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]]

What is the right way to filter based on a field/column?

thor
  • 21,418
  • 31
  • 87
  • 173

0 Answers0