0

I have the following array:

[[4 9]
 [5 4]
 ...
 [2 9]]

I want to filter this arr array, in a way, that I only have the elements of it, where both elements are between 0 and 7, and discard the rest. My solution, so far, has been to create a filter array, to index it with:

filter_array = ((arr >= 0) & (arr <= 7))

My problem is, this returns an array of the same shape as arr:

[[ True False]
 [ True True]
 ...
 [ True False]]

Which I can't use to index the original array in the way that I want. I want to discard the entire line, if any of the elements are not between the values I want:

#desired output:
[ False
  True
  ...
  False ]

I want to solve this in a "numpy-ish" manner, since the array is quite large, so performance is important. (I don't want to just iterate over it with some for loops)

1 Answer 1

1

You can sum in the axis=1 and see if it sums to 2:

filtered_array = (filtered_array.sum(1)==2)

Another way, where you can use and operator:

filtered_array = filter_array[:,0] & filter_array[:,1]

Lastly:

filter_array = filter_array.all(1)

This latter for me is the best way, but you can choose what works for you.

Sign up to request clarification or add additional context in comments.

2 Comments

In the first solution you proposed, you can just multiply each row to avoid checking the sum, namely filtered_array.prod(1) will give you 1 as result if and only if both elements are True.
@FBruzzesi, That's true, I guess it is kind of the same thing .all(1) do under the hoods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.