kristinek
kristinek

Reputation: 49

Indexing a multi dimensional array in Numpy

I'm a little confused on indexing in python. I have the following array

[[ 2  4]
 [ 6  8]
 [10 12]
 [14 16]]

and I want to obtain array([4, 2]) as my output. I tried using

Q4= [Q3[0,1],Q3[0,0]]

and my output come out as [4, 2]. I'm missing "array ("Any pointers on indexing in Python ? Thanks!!

Upvotes: 2

Views: 87

Answers (2)

Roy Smart
Roy Smart

Reputation: 694

While one option would be to just wrap your result in another call to numpy.array(),

np.array([Q3[0,1],Q3[0,0]])

it would be better practice and probably more performant to use integer advanced indexing. In that case, you can just use your indices from before to make one vectorized call to numpy.ndarray.__getitem__ (instead of two independent calls).

Q3[[0, 0], [1, 0]]

Edit: RomanPerekhrest's answer is definitely better in this situation, my answer would only be useful for arbitrary array indices.

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

Just slice the 1st row reversed:

Q3[0,::-1]

array([4, 2])

Upvotes: 2

Related Questions