简体   繁体   English

整数数组索引在numpy中如何工作?

[英]How does integer-array indexing work in numpy?

I am not able to understand integer array indexing in numpy. 我无法理解numpy中的整数数组索引。

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

Please explain me what is happening in this? 请解释一下这是怎么回事?

x[[0,1,2],[0,1,0]] 

[0,1,2] <- here you specify which arrays you will be using [0,1,0] <- here you choose elements from each of specified arrays [0,1,2] <-在这里您将指定要使用的数组[0,1,0] <-在这里您从每个指定的数组中选择元素

So element 0 from array 0, element 1 form arr 1 and so on 因此数组0中的元素0,元素1形成了arr 1,依此类推

In [76]: x = np.array([[1, 2], [3, 4], [5, 6]])
In [77]: x
Out[77]: 
array([[1, 2],
       [3, 4],
       [5, 6]])

Because the 1st and 2nd indexing lists match in size, their values are paired up to select elements from x . 由于第一和第二索引列表的大小匹配,因此将它们的值配对以从x选择元素。 I'll illustrate it with list indexing: 我将通过列表索引进行说明:

In [78]: x[[0, 1, 2], [0, 1, 0]]
Out[78]: array([1, 4, 5])
In [79]: list(zip([0, 1, 2], [0, 1, 0]))
Out[79]: [(0, 0), (1, 1), (2, 0)]
In [80]: [x[i,j] for i,j in zip([0, 1, 2], [0, 1, 0])]
Out[80]: [1, 4, 5]

Or more explicitly, it is returning x[0,0] , x[1,1] and x[2,0] , as a 1d array. 更确切地说,它将返回x[0,0]x[1,1]x[2,0]作为一维数组。 Another way to think it is that you've picked the [0,1,0] elements from the 3 rows (respectively). 另一种思维方式是,您分别从3行中选择了[0,1,0]元素。

I find it easiest to understand as follows: 我发现最容易理解如下:

In [179]: x = np.array([[1, 2], [3, 4], [5, 6]])                                                                     

In [180]: x                                                                                                          
Out[180]: 
array([[1, 2],
       [3, 4],
       [5, 6]])

Say we want to select 1 , 4 , and 5 from this matrix. 说,我们要选择145 ,从这个矩阵。 So the 0th column of row 0, the 1st column of the 1st row, and the 0th column of the 2nd row. 因此,第0行的第0列,第1行的第1列和第2行的第0列。 Now provide the index with two arrays (one for each dimension of the matrix), where we populate these arrays with the rows and then the columns we are interested in: 现在为索引提供两个数组(矩阵的每个维度一个),在这里我们用行然后是我们感兴趣的列填充这些数组:

In [181]: rows = np.array([0, 1, 2])                                                                                 

In [182]: cols = np.array([0, 1, 0])                                                                                 

In [183]: x[rows, cols]                                                                                              
Out[183]: array([1, 4, 5])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM