# Numpy element wise comparison for a particular value in two arrays [closed]

If I have two arrays as shown below:

a = numpy.array([0, 0, 1, 0, 1, 1, 1, 0, 1])
b = numpy.array([1, 1, 1, 0, 0, 1, 1, 0, 0])


Is there an easy way using numpy to count the number of occurrences where elements at the same index in each of the two arrays have a value equal to one. In the above two arrays, the elements in position(zero-indexed) 2, 5 and 6 are equal to 1 in both the arrays. Thus I want to get a count of 3 here.

Thank you for any help that you may be able to provide.

• This question is not about data-science, it is purely about code and belongs in stackoverflow. – Mark.F Jan 14 '19 at 12:06

There are two ways I'll show you (there are probably a lot more using NumPy):

## First method: chaining operations

You can use "masking" followed by the comparison and finally a sum operation:

We want all values in a from the indices where b is equal to 1:

part1 = a[b == 1]


Now we want all places where part1 is equal to 1

part2 = part1[part1 == 1]


now we are left with all the places where a and b are equal to 1, so we can simply sum them up:

result = part2.sum()


## Method 2: built in numpy.where

This is much shorted and probably faster to compute. NumPy has a nice function that returns the indices where your criteria are met in some arrays:

condition_1 = (a == 1)
condition_2 = (b == 1)


Now we can combine the operation by saying "and" - the binary operator version: &.

part1 = numpy.where(condition_1 & condition_2)


To get your desired output, we can take the length of the resulting set of indices:

result = len(part1)


Read the documentation about numpy.where to see the other things it can do for you!

sum(a * b)


Should do the job:)

As pointed out by @n1k31t4 it only works if you have two arrays that contain only 0 and 1. Otherwise you would have to write something like:

 sum((a == 1) * (b ==1))


What I find interesting here is that the sum functions treats boolean vectors as vectors with 0 (for False) and 1 (for True) on which you can perform arithmetic operation (+ for or, * for and etc..)

• This is an elegant solution, but only happens to work because OP used 0 and 1 in his example ;) – n1k31t4 Jan 14 '19 at 13:46

I like @RobinNicole's answer - in terms of Mathematics you are looking for a product of two boolean vectors.

Here are a few Numpy ways to do that:

In : np.dot(a, b)
Out: 3

In : a @ b
Out: 3


Here is another more generic solution which will work also for not-boolean vectors:

In : ((a == 1) & (b == 1)).sum()
Out: 3

• This is an elegant solution, but only happens to work because OP used 0 and 1 in his example ;) – n1k31t4 Jan 14 '19 at 13:46
• @n1k31t4, absolutely! That's why I marked word "boolean" as italian ;) I've also added a more generic Numpy solution – MaxU Jan 14 '19 at 13:48