72

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)

falsetru
  • 357,413
  • 63
  • 732
  • 636
Shai Zarzewski
  • 1,638
  • 3
  • 19
  • 33

2 Answers2

121

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
falsetru
  • 357,413
  • 63
  • 732
  • 636
32

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

np.count_nonzero(A==B)
jdehesa
  • 58,456
  • 7
  • 77
  • 121
  • 3
    This is by far the faster solution, as long as you know the arrays are the same length. – Andrew Guy Jul 06 '16 at 06:10
  • @AndrewGuy What if the arrays didn't have the same length? – Euler_Salter Aug 29 '17 at 09:42
  • 2
    @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])`. – jdehesa Aug 29 '17 at 09:45
  • @jdehesa thank you for your quick answer. Actually, I don't mind too much about their position. I would just like to know how many items in an array a, are in another array b. For instance if `a = np.array([4,1,2])` and if `b=np.array([1,2,3,4,5,6])` then when checking how many elements of `a` are in `b`, it should return 3 – Euler_Salter Aug 29 '17 at 09:47
  • 1
    @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))`. – jdehesa Aug 29 '17 at 09:55
  • @jdehesa thank you! If you want to help, here is the question: https://stackoverflow.com/questions/45936138/check-how-many-numpy-array-within-a-numpy-array-are-equal-to-other-numpy-arrays I just posted it – Euler_Salter Aug 29 '17 at 10:00
  • 2
    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 – Ignacio Alorre Dec 06 '20 at 18:15