Enryu
Enryu

Reputation: 1424

Numpy Sum when each array has a specific value

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.

Upvotes: 2

Views: 699

Answers (2)

atline
atline

Reputation: 31664

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

np.sum(np.logical_and((x1 == 1), (y == -1)))

Upvotes: 1

michcio1234
michcio1234

Reputation: 1838

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

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

This gives 3 as a result.

Upvotes: 6

Related Questions