2

I have an array as :

A
Out[159]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 2,  4,  6,  8, 10, 12, 14, 16]])

Now if I find the shape of :

A[0:1].shape
Out[150]: (1, 8)

While, if i try the same for

A[ [0,0,1,1], [0,3,2,5] ].shape
Out[151]: (4,)

First array seems to be 1 row and 8 columns and the second one seems to be 1 row and 4 columns, then why is the second answer shown as (4,) and not as (1,4) ?

1 Answer 1

1

The second case doesn't mean what you think it means.

The way this kind of fancy-indexing works in numpy is as follows: If A is a 2dim array and I1 = [a1, a2, ...] and I2 = [b1, b2, ...] are arrays/lists of ints, this indexing:

A[I1,I2]

means:

np.array([ A[a1,b1], A[a2,b2], A[a3,b3], ... ])

I1 refers to indexes along dim=0, and I2 refers to the corresponding indexes along dim=1. This means each [a_k, b_k] pair defines a single element to include in sliced array.


Another way to think about this: think about the tuple returned by np.where, and what you expect this to mean:

A[np.where(A == x)]
Sign up to request clarification or add additional context in comments.

2 Comments

but then what does Out[151]: (4,) mean actually ?
@Sarang it means a 1dim array of size 4. Since in your case len(I1)==len(I2)==4, you "pick" 4 elements from A

Your Answer

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.