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)

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

Like to comment? Feel free to send me an email or reach out on Twitter.

Did this or another article help you? If you like and can afford it, you can buy me a coffee (3 EUR) ☕️ to support me in writing more posts. In case you would like to contribute more or I helped you directly via email or coding/troubleshooting session, you can opt to give a higher amount through the following links or adjust the quantity: 50 EUR, 100 EUR, 500 EUR. All links redirect to Stripe.