[SOLVED] Indexing multidimensional Numpy array with another array


Consider the following numpy array.

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

When I index the array as follow, it produces another array with expected shape

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

But when I index it with another numpy array but with similar elements, it produces a different array, which is transpose of the above result.

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

I couldn’t understand why this is the case.


Tim Roberts summarized it excellently in the comments, which I’ll quote here in case the comments are cleaned up:

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].

In addition, if you notice, the two different indexing methods actually produce equivalent results; they’re just transposed versions of each other. So a[0, :, np.arange(5)] == a[0, :, 0:5].T and a[0, :, np.arange(5)].T == a[0, :, 0:5].

Answered By – richardec

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *