Deba
Deba

Reputation: 609

how numpy index is working

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]]])

Upvotes: 0

Views: 59

Answers (1)

user2357112
user2357112

Reputation: 280182

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.

Upvotes: 2

Related Questions