0

In the numpy tutorial from Scipy, while teaching fancy indexing of numpy arrays, I got the following explanation diagram.

enter image description here

As no other explanation about this particular array is given there, I have created the array using

a = np.array([[j+i for i in range(0,6)] for j in range(0, 60, 10)])

If I run a[(0,1,2,3,4),(1,2,3,4,5)] I am getting array([ 1, 12, 23, 34, 45]), consistent with the picture. But I can not understand how the tuples are getting unpacked to a[0,1] and so on.

I am trying to understand the mechanism of this. An in-depth answer will be much appreciated.

anotherone
  • 680
  • 1
  • 8
  • 23

1 Answers1

2

All fancy indexing does is essentially give you a list of co-ordinates in the larger array. So think of that picture as a big grid and your two tuples as x-coordinates and y-coordinates (it generalizes to higher dimensions too). So if you zip them together you get:

(x=0, y=1), (x=1, y=2), (x=2, y=3), (x=3, y=4), (x=4, y=5)

which if you read off the image you will see gives you:

(1, 12, 23, 34, 45)

as expected

Sven Harris
  • 2,884
  • 1
  • 10
  • 20
  • How they are getting zipped without any explicit zip command? – anotherone Sep 24 '18 at 19:22
  • 1
    That's it! Another way to understand this is thinking that the first tuple contains which rows that you will get and the second tuple contains which columns you will get from the array. Them they are paired up to do the slice. – Hemerson Tacon Sep 24 '18 at 19:23
  • @anotherone not sure how the internals are handled by numpy, it's just a way to think about how the tuples you pass the function can be interpreted in an understandable way. It's just how the numpy API was designed, it could equally have been designed to take individual co-ordinates as described. – Sven Harris Sep 24 '18 at 19:33
  • @SvenH. Yeah, I also got that and mentioned that in the question. But this 2 tuple structure seems a bit strange to me, and I have not seen it in any other place(without explicit zip) in python in my limited experience. – anotherone Sep 24 '18 at 19:38