平等比较两个numpy的阵列

平等比较两个numpy的阵列

本文介绍了平等比较两个numpy的阵列,逐元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是平等的地方被定义为能够比较平等的两个numpy的阵列(最简单的方法:A = B当且仅当所有的索引i: A [I] == B〔I] )?

只需用 == 给我一个布尔数组:

 >>> numpy.array([1,1,1])== numpy.array([1,1,1])阵列([真,真,真],DTYPE =布尔)

我必须此数组中的元素,以确定阵列是平等的,或者是有一个简单的比较方法是什么?


解决方案

 (A == B)。所有()

测试,如果阵列的所有值(A == B)是正确的。

修改(从dbaupp的答案,并yoavram的评论)

应当指出的是:


  • 这个解决方案可以在一个特定的情况下,一个奇怪的现象:如果 A B 为空,另外一个包含一个元素,那么它返回。出于某种原因,比较 A ==乙返回一个空数组,为此,所有运算符返回

  • 另一个风险是,如果 A B不具有相同的形状,并且不broadcastable,然后这种做法将引发一个错误。

在最后,我提出的解决方案是标准之一,我想,但如果你有一个关于 A B 形状或只是想安全:使用专门的功能之一:

  np.array_equal(A,B)#测试,如果形状相同,相同的元素值
np.array_equiv(A,B)#测试,如果broadcastable造型,相同的元素值
np.allclose(A,B,...)#测试,如果形状相同,内容有密切的足够的值

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()

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

这篇关于平等比较两个numpy的阵列,逐元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:17