1

Suppose I have two (sample) arrays in the following manner:

a = np.array([4, 5,-1, 2, -3, 3, -4])
b = np.array([0, 1, 0, 0, 1, 1, 0])

Now, I want to calculate the count of occurrences where (a > 0 and b == 0) and also where (a < 0 and b == 1). How can I condition an array based on values of two different arrays? If I try this:

a[a < 0 and b == 1]

I get the error:

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

I can do it using loops, but I want to avoid it and see if there's a better way of doing this.

1 Answer 1

4

One can use the bitwise-and operator &. Take care to wrap the expressions in parentheses because & binds more tightly

a[(a < 0) & (b == 1)]

One can achieve the same behavior with numpy.logical_and.

mask = np.logical_and(a < 0, b == 1)
a[mask]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That solved the problem. The problem was in fact being caused by the absence of the parentheses around each condition.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.