Count elementwise matches for two NumPy arrays

less than 1 minute read

Let’s say we have two integer NumPy arrays and want to count the number of elementwise matches.

Here are our two arrays (NumPy imported as np):

>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([1, 2, 2, 2, 5, 6, 7, 9, 9])

To create a third (boolean) array that contains True for a match, and False otherwise, we can use the equality operator.

>>> a == b
array([ True,  True, False, False,  True,  True,  True, False,  True])

Given that, counting the number of matches is as easy as:

>>> np.count_nonzero(a==b)
6

(Another option would be to use the (slower) np.sum(a==b))

Leave a Comment