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,796
  • 5
  • 27
  • 40
zlpython
  • 29
  • 6
  • 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. – hpaulj Jun 20 '17 at 16:01
  • Possible duplicate of [Explain slice notation](https://stackoverflow.com/questions/509211/explain-slice-notation) – polka Jun 20 '17 at 16:21
  • No this isn't just a plain slice question. It's something more subtle. – hpaulj Jun 20 '17 at 16:30
  • https://stackoverflow.com/a/36208170/901925 – hpaulj Jun 20 '17 at 16:32

1 Answers1

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

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • 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. – zlpython Jun 21 '17 at 09:49
  • 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. – zlpython Jun 21 '17 at 10:04