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!