比较两个numpy数组用于相等,元素(Comparing two numpy arrays for equality, element

编程入门 行业动态 更新时间:2024-10-23 05:32:50
比较两个numpy数组用于相等,元素(Comparing two numpy arrays for equality, element-wise)

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

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

>>> numpy.array([1,1,1]) == numpy.array([1,1,1]) array([ True, True, True], dtype=bool)

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

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。

编辑 (从dbaupp的答案和yoavram的评论)

应该指出的是:

该解决方案在特定情况下可能会有一个奇怪的行为:如果A或B为空,另一个包含单个元素,则返回True 。 由于某些原因,比较A==B返回一个空数组, all操作符返回True 。 另一个风险是如果A和B的形状不一样,不可广播,那么这种方法会引起错误。

总而言之,我提出的解决方案是标准的,我认为,但是如果你对A和B形状有疑问,或者只是想要安全:使用一个专门的功能:

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 (A==B).all()

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

Edit (from dbaupp's answer and yoavram's comment)

It should be noted that:

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.

In conclusion, the solution I proposed is the standard one, I think, but 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

更多推荐

本文发布于:2023-08-07 20:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465972.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   两个   numpy   element

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!