比较两个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更多推荐
发布评论