问题描述
什么是平等的地方被定义为能够比较平等的两个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 $疑问C $ C>形状或只是想安全:使用专门的功能之一:
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
orB
is empty and the other one contains a single element, then it returnTrue
. For some reason, the comparisonA==B
returns an empty array, for which theall
operator returnsTrue
. - Another risk is if
A
andB
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的阵列,逐元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!