Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of unequal elements across numpy arrays

Tags:

python

numpy

Lets say I have two numpy arrays A and B:

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

I would like to (quickly) count the number of elements that are unequal between the two arrays. In the case above, the answer would be 2.

Is there nice way to do this?

like image 892
James Atwood Avatar asked Feb 24 '16 21:02

James Atwood


People also ask

How do you check if two NumPy arrays are equal?

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 count nonzero elements in a NumPy array?

count_nonzero() function counts the number of non-zero values in the array arr. Parameters : arr : [array_like] The array for which to count non-zeros. axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros.

Is there a count function in NumPy?

NumPy: count() function count() function returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end]. Input an array_like of string or unicode. The substring to search for.


1 Answers

From the related question you can also reverse the logic and do:

np.count_nonzero(A != B)

Which actually seems to be quite a bit more efficient.

like image 194
Padraic Cunningham Avatar answered Sep 30 '22 12:09

Padraic Cunningham