2

When I try to slice a Numpy array (3d), something unexpected occurs.

import numpy as np
x=np.array(
[   [[1., 2., 3., 4., 5.],
    [6., 7., 8., 9., 0.],
    [1., 2., 3., 4., 5.],
    [6., 7., 8., 9., 0.]],

[   [11., 12., 13., 14., 15.],
    [16., 17., 18., 19., 10.],
    [11., 12., 13., 14., 15.],
    [16., 17., 18., 19., 10.]],

[   [21., 22., 23., 24., 25.],
    [26., 27., 28., 29., 20.],
    [21., 22., 23., 24., 25.],
    [26., 27., 28., 29., 20.]]]
)
print(x.shape)  #(3,4,5)
print(x[:,0,[0,1,2,3,4]].shape) #(3,5) as expected 
print(x[0,:,[0,1,2,3,4]].shape) #(5,4) why not (4,5)?

The latest one swap the dimension unexpectedly. Why?

2 Answers 2

1

You are using a combination of two array indexing methods. The method that is commonly used in Python is the so called Basic Indexing, where you use slices m:n, and ellipsis ... to define a slice of an array. The other method is called Advanced Indexing where you use a tuple or a list to specify the selection. The difference between the two methods is that the Advanced indexing method generates a copy of the data, while the Basic indexing does not.

When combining basic and advanced indexing the memory layout of the array may change.

In your first example the dimensions that are treated as advanced indices are next to each other, so the shape is preserved.

In your second example the dimensions that are treated as advanced indices are interspersed with a dimension with basic indexing. So the advanced indexed dimensions come first in the result array.

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

Comments

1

It's in the docs

Quote:

Combining advanced and basic indexing

...

The easiest way to understand the situation may be to think in terms of the result shape. There are two parts to the indexing operation, the subspace defined by the basic indexing (excluding integers) and the subspace from the advanced indexing part. Two cases of index combination need to be distinguished:

  • The advanced indexes are separated by a slice, ellipsis or newaxis. For example x[arr1, :, arr2].
  • The advanced indexes are all next to each other. For example x[..., arr1, arr2, :] but not x[arr1, :, 1] since 1 is an advanced index in this regard.

In the first case, the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that. In the second case, the dimensions from the advanced indexing operations are inserted into the result array at the same spot as they were in the initial array (the latter logic is what makes simple advanced indexing behave just like slicing).

Unquote.

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.