gpt4 book ai didi

python - 这个 numpy 高级索引代码是如何工作的?

转载 作者:行者123 更新时间:2023-11-28 20:55:44 25 4
gpt4 key购买 nike

我正在学习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等于[[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

关于python - 这个 numpy 高级索引代码是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com