按元素比较两个 NumPy 数组的相等性 [英] Comparing two NumPy arrays for equality, element-wise

查看:104
本文介绍了按元素比较两个 NumPy 数组的相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较两个 NumPy 数组是否相等的最简单方法是什么(其中相等性定义为:A = B iff 对于所有索引 i:A[i] = B[i])?

What is the simplest way to compare two NumPy arrays for equality (where equality is defined as: A = B iff for all indices i: A[i] == B[i])?

简单地使用 == 给我一个布尔数组:

Simply using == gives me a boolean array:

 >>> numpy.array([1,1,1]) == numpy.array([1,1,1])

array([ True,  True,  True], dtype=bool)

我是否必须这个数组的元素来确定数组是否相等,或者有更简单的比较方法吗?

Do I have to and the elements of this array to determine if the arrays are equal, or is there a simpler way to compare?

推荐答案

(A==B).all()

测试数组 (A==B) 的所有值是否都为 True.

test if all values of array (A==B) are True.

注意:也许你还想测试A和B形状,比如A.shape == B.shape

Note: maybe you also want to test A and B shape, such as A.shape == B.shape

特殊情况和替代方案(来自 dbaupp 的回答和 yoavram 的评论)

Special cases and alternatives (from dbaupp's answer and yoavram's comment)

需要注意的是:

  • 此解决方案在特定情况下可能会出现奇怪的行为:如果 AB 为空,而另一个包含单个元素,则返回 .出于某种原因,比较 A==B 返回一个空数组,对于该数组,all 运算符返回 True.
  • 另一个风险是,如果 AB 没有相同的形状并且不可广播,那么这种方法会引发错误.
  • this solution can have a strange behavior in a particular case: if either A or B is empty and the other one contains a single element, then it return True. For some reason, the comparison A==B returns an empty array, for which the all operator returns True.
  • Another risk is if A and B don't have the same shape and aren't broadcastable, then this approach will raise an error.

总而言之,如果您对 AB 形状有疑问,或者只是想确保安全:请使用其中一种专用函数:

In conclusion, if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:

np.array_equal(A,B)  # test if same shape, same elements values
np.array_equiv(A,B)  # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values

这篇关于按元素比较两个 NumPy 数组的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆