首页 > 解决方案 > 如何在两个 NumPy 数组之间进行逐元素比较

问题描述

我有两个数组。我想在它们两者之间进行逐元素比较,以找出哪些值相同。

a= np.array([[1,2],[3,4]])
b= np.array([[3,2],[1,4]])

有没有办法让我将这两个数组与 1)找出哪些值相同,以及 2)获取相同值的索引?

加上上一个问题,如果值相同,我有没有办法返回 1,否则返回 0?

提前致谢!

标签: pythonarraysnumpy

解决方案


a= np.array([[1,2],[3,4]])
b= np.array([[3,2],[1,4]])

#1) find out which values are the same
a==b
# array([[False,  True],
#        [False,  True]])

#2) get the index of the same values?
np.where((a==b) == True) # or np.where(a==b)
#(array([0, 1]), array([1, 1]))

# Adding on to the previous question, is there a way for me to return 1 if the values are the same and 0 otherwise
(a==b).astype(int)
# array([[0, 1],
#        [0, 1]])

推荐阅读