首页 > 解决方案 > 这个 numpy 高级索引代码如何工作?

问题描述

我正在学习numpy框架。这段代码我看不懂。

import numpy as np
a =np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
print(a)
row = np.array([[0,0],[3,3]])
col = np.array([[0,2],[0,2]])
b = a[row,col]
print("This is b array:",b)

b数组返回数组的角值a,即b equals [[0,2],[9,11]]

标签: pythonpython-3.xnumpynumpy-indexingadvanced-indexing

解决方案


当使用数组或“类数组”完成索引以访问/修改数组的元素时,称为高级索引。

In [37]: a
Out[37]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

In [38]: row
Out[38]: 
array([[0, 0],
       [3, 3]])

In [39]: col
Out[39]: 
array([[0, 2],
       [0, 2]])

In [40]: a[row, col]
Out[40]: 
array([[ 0,  2],
       [ 9, 11]])

这就是你得到的。下面是一个解释:

              Indices of  
`a[row, col]` row  column  
   ||   ||    ||   ||
   VV   VV    VV   VV
  a[0,  0]   a[0,  2]   
  a[3,  0]   a[3,  2]
    |__________|   |
   row-idx array   |
        |__________| 
        column-idx array

推荐阅读