Python 为什么np.argwhere';s结果形状与它不匹配';谁的输入?

Python 为什么np.argwhere';s结果形状与它不匹配';谁的输入?,python,arrays,numpy,Python,Arrays,Numpy,假设我传递一个1D数组: >>> np.arange(0,20) array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) >>> np.arange(0,20).shape (20,) 其中: >>> np.argwhere(np.arange(0,20)<10) array([[0],

假设我传递一个1D数组:

>>> np.arange(0,20)
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])
>>> np.arange(0,20).shape
(20,)
其中:

>>> np.argwhere(np.arange(0,20)<10)
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
>>> np.argwhere(np.arange(0,20)<10).shape
(10, 1)

>>np.argwhere(np.arange(0,20)>>np.argwhere(np.arange(0,20)
argwhere
返回where条件为真的坐标。通常,坐标是元组,因此输出应该是2D

>>> np.argwhere(np.arange(0,20).reshape(2,2,5)<10)
array([[0, 0, 0],
       [0, 0, 1],
       [0, 0, 2],
       [0, 0, 3],
       [0, 0, 4],
       [0, 1, 0],
       [0, 1, 1],
       [0, 1, 2],
       [0, 1, 3],
       [0, 1, 4]])

>>np.argwhere(np.arange(0,20).重塑(2,2,5)
numpy.argwhere
查找满足条件的元素的索引。有些元素本身就是输出的元素(索引与值相同)

特别是,在您的示例中,输入是一维的,输出是一维(索引)乘以二(第二个是迭代值)

我希望这是清楚的,如果不是,以numpy文档中的二维输入数组为例:

>>> x = np.arange(6).reshape(2,3)
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.argwhere(x>1)
array([[0, 2],
       [1, 0],
       [1, 1],
       [1, 2]])

argwhere
只是
where
的转置(实际上
np.nonzero
):

In [17]: np.where(np.arange(0,20)<10)
Out[17]: (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),)
In [18]: np.transpose(_)
Out[18]: 
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
In [19]: x = np.arange(10).reshape(2,5)
In [20]: x %2
Out[20]: 
array([[0, 1, 0, 1, 0],
       [1, 0, 1, 0, 1]])
In [21]: np.where(x%2)
Out[21]: (array([0, 0, 1, 1, 1]), array([1, 3, 0, 2, 4]))
In [22]: np.argwhere(x%2)
Out[22]: 
array([[0, 1],
       [0, 3],
       [1, 0],
       [1, 2],
       [1, 4]])
In [23]: x[np.where(x%2)]
Out[23]: array([1, 3, 5, 7, 9])
In [24]: for i in np.argwhere(x%2):
    ...:     print(x[tuple(i)])
    ...:     
1
3
5
7
9
In [25]: [x[tuple(i)] for i in np.argwhere(x%2)]
Out[25]: [1, 3, 5, 7, 9]