用另一个数组索引多维 Numpy 数组

Indexing multidimensional Numpy array with another array

考虑以下 numpy 数组。

a = np.random.randn(10, 3, 20)

当我如下索引数组时,它会生成另一个具有预期形状的数组

b = a[0, :, 0:5]
b.shape = (3, 5)

但是当我用另一个具有相似元素的 numpy 数组对其进行索引时,它会生成一个不同的数组,该数组是上述结果的转置。

j = np.arange(0, 5, 1)
b = a[0, :, j]
b.shape = (5, 3)

我不明白为什么会这样。

Tim Roberts summarized it excellently in ,我会在这里引用以防评论被清理:

It's subtle. The second example is concatenating a set of slices. If you print a[0,:,0], you'll see a 3-element slice, equal to the first row of the final b. Same with a[0,:,1]. The magic indexing takes those 5 3-element slices and returns then in a new array. A set of 5 slices is different from the array subset in a[0,:,0:5].

此外,如果您注意到,这两种不同的索引方法实际上会产生相同的结果;它们只是彼此的转置版本。所以 a[0, :, np.arange(5)] == a[0, :, 0:5].Ta[0, :, np.arange(5)].T == a[0, :, 0:5].