0

I know that in Numpy you can mask an array based on a condition. For example, if I want a masked array for all values greater than 0.

arr[arr>0]

But I want to have two conditions for the mask. Intuitively, this would look like:

arr[arr>0 and arr<1]

but the compiler pops an error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I know I can use a for loop to solve this:

masked=np.array([i if(i>0 and i<1) for i in mask])

but is there a more elegant solution using something that's built-in for Numpy?

1 Answer 1

1

You want this:

arr[(arr > 0) & (arr < 1)]
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, I should have tried that. Is there an explanation as to why "and" doesn't work?
"and" expects to produce a scalar True/False. You want elementwise logic.
Interesting, now that you mentioned it I found a page that explains this in a similar scenario: stackoverflow.com/questions/8632033/….
and is a Python expression, more like a if/else clause than an operator. True and 1 returns 1, more like 1 if True else False. (except it short circuits)

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.