比较numpy数组的规则是什么

比较numpy数组的规则是什么

本文介绍了使用==比较numpy数组的规则是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,尝试弄清楚这些结果:

For example, trying to make sense of these results:

>>> x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> (x == np.array([[1],[2]])).astype(np.float32)
array([[ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]], dtype=float32)
>>> (x == np.array([1,2]))
   False
>>> (x == np.array([[1]])).astype(np.float32)
array([[ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]], dtype=float32)
>>> (x == np.array([1])).astype(np.float32)
array([ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.], dtype=float32)

>>> (x == np.array([[1,3],[2]]))
False
>>>

这是怎么回事?在[1]的情况下,它将1与x的每个元素进行比较,并将结果汇​​总到一个数组中.对于[[1]],同样的事情.仅通过对repl进行试验,就很容易弄清楚特定阵列形状会发生什么.但是,双方可以具有任意形状的基本规则是什么?

What's going on here? In the case of [1], it's comparing 1 to each element of x and aggregating the result in an array. In the case of [[1]], same thing. It's easy to figure out what's going to occur for specific array shapes by just experimenting on the repl. But what are the underlying rules where both sides can have arbitrary shapes?

推荐答案

NumPy会在比较之前尝试将两个数组广播为兼容形状.如果广播失败,则当前返回False. 在未来

NumPy tries to broadcast the two arrays to compatible shapes before comparison.If the broadcasting fails, False is currently returned. In the future,

否则,将返回由逐个元素比较得出的布尔数组.例如,由于xnp.array([1])是可广播的,因此将返回形状(10,)的数组:

Otherwise, a boolean array resulting from the element-by-element comparison is returned. For example, since x and np.array([1]) are broadcastable, an array of shape (10,) is returned:

In [49]: np.broadcast(x, np.array([1])).shape
Out[49]: (10,)

由于xnp.array([[1,3],[2]])不可广播,因此Falsex == np.array([[1,3],[2]])返回.

Since x and np.array([[1,3],[2]]) are not broadcastable, False is returned by x == np.array([[1,3],[2]]).

In [50]: np.broadcast(x, np.array([[1,3],[2]])).shape
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-50-56e4868cd7f7> in <module>()
----> 1 np.broadcast(x, np.array([[1,3],[2]])).shape

ValueError: shape mismatch: objects cannot be broadcast to a single shape

这篇关于使用==比较numpy数组的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:46