numpy.where返回元组的目的是什么? [英] What is the purpose of numpy.where returning a tuple?
问题描述
当我运行此代码时:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
print(np.where(a > 2))
自然会得到一个索引数组,其中 a>2
,即 [2,3,4,5]
,但是我们得到:
it would be natural to get an array of indices where a > 2
, i.e. [2, 3, 4, 5]
, but instead we get:
(array([2, 3, 4, 5], dtype=int64),)
即具有空第二个成员的元组.
i.e. a tuple with empty second member.
然后,要获得 numpy.where
的自然"答案,我们必须做:
Then, to get the the "natural" answer of numpy.where
, we have to do:
np.where(a > 2)[0]
该元组有什么意义?在哪种情况下有用?
注意:我在这里只谈论用例 numpy.where(cond)
,而不是同样存在的 numpy.where(cond,x,y)
(请参阅文档).
Note: I'm speaking here only about the use case numpy.where(cond)
and not numpy.where(cond, x, y)
that also exists (see documentation).
推荐答案
numpy.where
返回一个元组,因为该元组的每个元素都引用一个维度.
numpy.where
returns a tuple because each element of the tuple refers to a dimension.
请从2维角度考虑此示例:
Consider this example in 2 dimensions:
a = np.array([[1, 2, 3, 4, 5, 6],
[-2, 1, 2, 3, 4, 5]])
print(np.where(a > 2))
(array([0, 0, 0, 0, 1, 1, 1], dtype=int64),
array([2, 3, 4, 5, 3, 4, 5], dtype=int64))
如您所见,元组的第一个元素指的是相关元素的第一个维度;第二个元素是第二个维度.
As you can see, the first element of the tuple refers to the first dimension of relevant elements; the second element refers to the second dimension.
这是 numpy
经常使用的约定.当您要求数组的形状时,您也会看到它,即一维数组的形状将返回包含1个元素的元组:
This is a convention numpy
often uses. You will see it also when you ask for the shape of an array, i.e. the shape of a 1-dimensional array will return a tuple with 1 element:
a = np.array([[1, 2, 3, 4, 5, 6],
[-2, 1, 2, 3, 4, 5]])
print(a.shape, a.ndim) # (2, 6) 2
b = np.array([1, 2, 3, 4, 5, 6])
print(b.shape, b.ndim) # (6,) 1
这篇关于numpy.where返回元组的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!