2
x1 = np.array([0,  1,  0,  1,  0, 1, 0, 1, 1,  1])
y = np.array([-1, -1, -1, -1, -1, 1, 1, 1, 1, -1])

I know with these 2 arrays you can sum up the amount of times exact indicies are equal with numpy in this line of code.

np.sum(x1 == y)

but is there a way to sum up each time the same index equals a specific value on each array such as

np.sum(x1 == 1 && y == -1)

Unfortunately this line of code doesn't run, but if it worked the result should be 3.

2 Answers 2

6

You just have to use a single & and add some parentheses:

np.sum((x1 == 1) & (y == -1))

This gives 3 as a result.

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

Comments

1

Besides a & b in numpy, you may also use logical_and, just FYI.

np.sum(np.logical_and((x1 == 1), (y == -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.