1

I think I understand the indexing of array in python/numpy correctly. But today I met a problem as follows:

I have a 6-d array e.g. A and A.shape = (11,1,9,1,5,7). Then I use the indexing as follows:

B = A[:,0,0,0,[3,4,2],0] 

and B.shape = (11,3) as expected;

C = A[:,0,0,0,[3,4,2],:] 

and C.shape = (11,3,7) as expected;

But when I say:

D = A[:,0,:,0,[3,4,2],0] 

and D.shape should be (11,9,3) as I can expect, however, python returned the D.shape = (3, 11, 9).

And I'm really confused about the shape of array D.

Is there any one can give me a brief explanation? Thanks a lot!

Dadep
2,7805 gold badges30 silver badges40 bronze badges
asked Jun 20, 2017 at 15:41
4
  • 1
    There's a section in the basic&advanced indexing docs about mixing slices and lists. There's some ambiguity, and numpy opts to put the slice dimensions last. This behavior has also been discussed in previous SO questions. Commented Jun 20, 2017 at 16:01
  • Possible duplicate of Explain slice notation Commented Jun 20, 2017 at 16:21
  • No this isn't just a plain slice question. It's something more subtle. Commented Jun 20, 2017 at 16:30
  • stackoverflow.com/a/36208170/901925 Commented Jun 20, 2017 at 16:32

1 Answer 1

2

As discussed in https://docs.scipy.org/doc/numpy-1.12.0/reference/arrays.indexing.html#combining-advanced-and-basic-indexing

A[:,0,:,0,[3,4,2],0]

indexes with the 'advanced' list, [3,4,2] producing the size 3 dimension. And the 1st and 3rd dimensions are added on after, resulting in the (3,11,9) shape.

This behavior is somewhat controversial, especially when the other indices are scalars. The justification given in the docs is clearer when there are two indexing lists.

Numpy sub-array assignment with advanced, mixed indexing

answered Jun 20, 2017 at 17:40

2 Comments

Hi hpaulj, thanks a lot for the answer. Now I get the point that be careful when using a combination of a slice and seq. of integers.
And for array B and C, the slice was also used (but only in the first and last dimension) combining with other scalar indices, which works in the way i can normally expect. However, for array D a slice was used between scalar indices, I guess this is the reason which make the array shape resulted in the other behavior. BUT regarding this syntax, it is still very easy to be confused.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.