Python中要索引的其他表单

Python中要索引的其他表单,python,numpy,indexing,Python,Numpy,Indexing,我正在学习一门机器学习课程,在对numpy图书馆的回顾中,使用了一种我从未见过的索引方法。我们定义了a=np.array([[1,2],[3,4],[5,6]])。随后创建了两个新数组:np.array([a[0,0],a[1,1],a[2,1]]]。这是我知道的索引方式。我不知道的索引方式是:print(a[[0,1,2],[0,1,1]])。有人能帮我解释一下这种最新的索引形式吗?当传递n数组时,其中n是数组维度的数目,它们被用作相应维度的索引。a[[0,1,2],[0,1,1]]相当于[a

我正在学习一门机器学习课程,在对numpy图书馆的回顾中,使用了一种我从未见过的索引方法。我们定义了
a=np.array([[1,2],[3,4],[5,6]])
。随后创建了两个新数组:
np.array([a[0,0],a[1,1],a[2,1]]]
。这是我知道的索引方式。我不知道的索引方式是:
print(a[[0,1,2],[0,1,1]])
。有人能帮我解释一下这种最新的索引形式吗?

当传递
n
数组时,其中
n
是数组维度的数目,它们被用作相应维度的索引。
a[[0,1,2],[0,1,1]]
相当于
[a[0,0],a[1,1],a[2,1]

让我引用以下文件:

…应从每行中选择一个特定元素。该行 索引仅为[0,1,2],列索引指定要添加的元素 选择对应行,此处为[0,1,0]。同时使用这两个选项 可以使用高级索引解决该任务:

它调用。在您的示例中,您正在访问一个名为
a
的1x3数组的
[[0,1,2],[0,1,1]
索引。这意味着您正在从
a
获取:

[
    the first element of the first array,contained in this 1x3 array,
    the second element of the second array, contained in this big array,
    the second element of the third array, contained in the same array
]
打印输出时,您将获得
[1 4 6]
的输出,因为这些元素位于指定位置(
(0,0)
(1,1)
(2,1)
)。您可以将其可视化为列和行方案:


您可以在第一个子数组中选择所需项目的行,在第二个子数组中选择列。

这是另一个非常好地解释索引的教程:
[
    the first element of the first array,contained in this 1x3 array,
    the second element of the second array, contained in this big array,
    the second element of the third array, contained in the same array
]
[[rows],[colums]] # vertically speaking