首页 > 解决方案 > Python中索引的其他形式

问题描述

我正在学习机器学习课程,并且在回顾 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]]). 有人可以帮我解释一下这种最新的索引形式吗?

标签: pythonnumpyindexing

解决方案


它调用整数数组索引。在您的示例中,您正在访问[[0,1,2],[0,1,1]]一个 1x3 数组的索引,称为a. 这意味着,您来自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))。您可以将其可视化为列和行方案

[[rows],[colums]] # vertically speaking

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


推荐阅读