检查在两个numpy数组python中有多少元素是相等的

时间:2022-04-04 12:08:46

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)

然后我希望返回值为2(只有1和2在位置和值上相等)

2 个解决方案

#1


50  

Using numpy.sum:

使用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

#2


14  

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

只要两个数组都保证具有相同的长度,就可以这样做:

np.count_nonzero(A==B)

#1


50  

Using numpy.sum:

使用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

#2


14  

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

只要两个数组都保证具有相同的长度,就可以这样做:

np.count_nonzero(A==B)