check how many elements are equal in two numpy arrays python

PythonArraysNumpy

Python Problem Overview


I have two numpy arrays with number (Same length), and I want to count how many elements are equal between those two array (equal = same value and position in array)

A = [1, 2, 3, 4]
B = [1, 2, 4, 3]

then I want the return value to be 2 (just 1&2 are equal in position and value)

Python Solutions


Solution 1 - Python

Using numpy.sum:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4])
>>> b = np.array([1, 2, 4, 3])
>>> np.sum(a == b)
2
>>> (a == b).sum()
2

Solution 2 - Python

As long as both arrays are guaranteed to have the same length, you can do it with:

np.count_nonzero(A==B)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShai ZarzewskiView Question on Stackoverflow
Solution 1 - PythonfalsetruView Answer on Stackoverflow
Solution 2 - PythonjdehesaView Answer on Stackoverflow