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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With