python - 这个 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]]
。
解决方案
当使用数组或“类数组”完成索引以访问/修改数组的元素时,称为高级索引。
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
推荐阅读
- ssl - 如何使用带有 nginx-ingress 的数字证书来启用 https
- python - 无法导入我刚刚安装的 Python 模块
- ruby - 将用户输入添加到哈希中
- nfc - Felica Card 错误:无法访问命令指定的区域或服务
- sql - 向有序交易组添加唯一 ID
- python - 无法从 sklearn 导入任何模型
- uppercase - 在这种情况下如何获得上str
- c - 函数的行为就像它破坏了 if 语句中的表
- google-sheets - 我想计算有多少结果“失败”或“通过”并按日期组织它们
- docker - docker-in-docker 卷上的 $(pwd) 挂载了意外的目录