0

I was checking indexing in numpy array but got confused in below case, please tell me why I am getting different output when I am converting a list to an array. what am I doing wrong?

In [124]: a = np.arange(12).reshape(3, 4)
Out[125]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [126]: j = [[0, 1], [1, 2]]

In [127]: a[j]
Out[127]: array([1, 6])

In [128]: a[np.array(j)]
Out[128]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 4,  5,  6,  7],
        [ 8,  9, 10, 11]]])
Deba
  • 609
  • 8
  • 17
  • hi, try to read it here, it is quite comprehensive: https://docs.scipy.org/doc/numpy-1.10.0/user/basics.indexing.html – Radek Hofman Aug 21 '17 at 18:38
  • It's also discussed here https://stackoverflow.com/questions/45675801/why-does-numpy-advanced-indexing-yield-different-results-for-list-of-lists-and-n#comment78316662_45675801 and here https://stackoverflow.com/questions/40598824/advanced-slicing-when-passed-list-instead-of-tuple-in-numpy – hpaulj Aug 21 '17 at 19:06
  • @hpaulj, Thank you for the references. – Deba Aug 21 '17 at 19:28

1 Answers1

2

There's a bit of undocumented backward compatibility handling where if the selection object is a single short non-ndarray sequence containing embedded sequences, the sequence is handled as if it were a tuple. That means this:

a[j]

is treated as

a[[0, 1], [1, 2]]

instead of as the docs would have you expect.

user2357112
  • 260,549
  • 28
  • 431
  • 505