I need to compare two arrays made only by 0 and 1:
A = [0,1,0,0,1]
B = [1,1,0,0,1]
I want to get the number of elements that aren't equals and the percentage, i tried this code:
print(numpy.mean(A == B))
but sometimes i get 0 when some elements are equal...
CodePudding user response:
To get the number of elements that aren't equal in the two lists index wise, you can do this :
noneq = sum(i==j for i, j in zip(A, B))
To get the percentage, you can simple calculate noneq/len(A)
or noneq/len(B)
CodePudding user response:
You could use list comprehension to create list of whether the values in indexes are equal and then calculate the mean of the said list.
numpy.mean([x == y for x, y in zip(A, B)])
CodePudding user response:
import numpy as np
A = np.array([0,1,0,0,1])
B = np.array([1,1,0,0,1])
# number of
(A!=B).sum() #1
# percentage
(A!=B).sum()*100 / A.size
CodePudding user response:
use count_nonzero
to Count the number of elements satisfying the condition
A = np.array([0,1,0,0,1])
B = np.array([1,1,0,0,1])
print(np.count_nonzero((A==B) == True))
for the percentage use np.count_nonzero/shape
CodePudding user response:
While list comprehension is always the most elegant solution - also esthetically, in my view - I found the following slightly faster:
def calc(v1, v2):
s = 0
for i, x in enumerate(v1):
s = x == v2[i]
return s / len(v1)
Clearly, in all cases, you should always check/be aware of what happens if A
and B
hace different lengths (for example, the code I have just share would return an IndexError
if len(v1) > len(v2)
; in that respect, zip
behaves differently in different version of python)