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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25490641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:17:55  来源:igfitidea点击:

check how many elements are equal in two numpy arrays python

pythonarraysnumpy

提问by Shai Zarzewski

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)

我有两个带有数字(相同长度)的 numpy 数组,我想计算这两个数组之间有多少个元素相等(相等 = 数组中的相同值和位置)

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 在位置和值上相等)

采纳答案by falsetru

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

回答by jdehesa

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

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

np.count_nonzero(A==B)