3

How to filter an array A according to two conditions ?

A = array([1, 2.3, 4.3, 10, 23, 42, 23, 12, 1, 1])
B = array([1, 7, 21, 5, 9, 12, 14, 22, 12, 0])
print A[(B < 13)]      # here we get all items A[i] with i such that B[i] < 13
print A[(B > 5) and (B < 13)]   # here it doesn't work
                                # how to get all items A[i] such that B[i] < 13 
                                # AND B[i] > 5 ?

The Error is:

ValueError: The truth value of an array with more than one element is ambiguous.

2 Answers 2

5

You should use the bitwise (thanks @askewchan) version of the operator and which is &.

i.e.

 print A[(B > 5) & (B < 13)] 
Sign up to request clarification or add additional context in comments.

2 Comments

In numpy (and python in general), & isn't a set operator, actually it's a bitwise operator. Here, it works only because we're comparing two boolean arrays as a string of bits with 1-bit elements. It is the equivalent to saying np.bitwise_and, not np.logical_and as @larsmans has answered. You might find the behavior unexpected if you do something like np.array([0,1,2]) & np.array([True, True, True])
@askewchan, thanks for your explanation. I corrected my answer.
5
>>> A[np.logical_and(B > 5, B < 13)]
array([  2.3,  23. ,  42. ,   1. ])

Comments

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.