75

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)

2 Answers 2

124

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
Sign up to request clarification or add additional context in comments.

6 Comments

How can I extend this to make it work with 2D arrays?
@NicolasSchejtman The solution in the answer should work for 2d arrays. Try a = np.array([[1,2,0],[3,4,0]]); b = np.array([[1,9,0],[9,4,0]]); print((a == b).sum())
and what if there are of different shapes and at different indexes? i.e. b = np.array([3, 2, 4, 1, 1])
@user5173426, np.sum(a[:min(len(a), len(b))] == b[:min(len(a), len(b))])
I am getting 'bool' object has no attribute 'sum'
|
34

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

np.count_nonzero(A==B)

7 Comments

This is by far the faster solution, as long as you know the arrays are the same length.
@AndrewGuy What if the arrays didn't have the same length?
@Euler_Salter Assuming you want to count elements with same value and position, I guess just something like s = min(len(A), len(B)); count = np.count_nonzero(A[:s] == B[:s]).
@Euler_Salter Ah that's a different problem (surely there is a question with better answers out there...). If they do not have repeated elements, one simple way (not sure if necessarily the best) is np.count_nonzero(np.logical_or.reduce(A[:, np.newaxis], B[np.newaxis, :], axis=0)).
Just for the record, if anyone is getting the warning: 'DeprecationWarning: elementwise comparison failed; this will raise an error in the future', and 0 value in the sum result, check the lenght of your "a" and "b", since they may be of different length
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.