Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check how many elements are equal in two numpy arrays python

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)

like image 391
Shai Zarzewski Avatar asked Aug 25 '14 16:08

Shai Zarzewski


People also ask

How do you compare elements of two NumPy arrays?

To check if two NumPy arrays A and B are equal: Use a comparison operator (==) to form a comparison array. Check if all the elements in the comparison array are True.

How do I check if two NumPy arrays are the same?

Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray. all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent.

How do you find the common elements in two NumPy arrays in Python?

In NumPy, we can find common values between two arrays with the help intersect1d(). It will take parameter two arrays and it will return an array in which all the common elements will appear.


2 Answers

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 
like image 110
falsetru Avatar answered Sep 22 '22 06:09

falsetru


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

np.count_nonzero(A==B) 
like image 26
jdehesa Avatar answered Sep 18 '22 06:09

jdehesa