2

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!!

2 Answers 2

2

Just slice the 1st row reversed:

Q3[0,::-1]

array([4, 2])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

I think your example is more insightful for OP. +1
Thanks @Chrysophylaxs. It's definitely important to know both methods and recognize when you can use slicing vs. when to resort to integer indexing.

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.