2

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.

10
  • Quite interesting. I'm observing this behaviour as well, but I'm not enough of a numpy expert to understand the cause. I'll poke around and see if I can determine more. Commented Mar 15, 2022 at 21:15
  • 1
    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]. Commented Mar 15, 2022 at 21:17
  • 1
    So it seems like both versions are actually just tranposed version of the eachother. Commented Mar 15, 2022 at 21:20
  • 1
    @richardec Thanks! I accepted it as a valid answer. Commented Mar 15, 2022 at 22:47
  • 2
    Mixed advanced and basic indexing bites again :) numpy.org/doc/stable/user/… Commented Mar 15, 2022 at 23:13

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.