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

asked Jan 29, 2023 at 20:14

2 Answers 2

2

Just slice the 1st row reversed:

Q3[0,::-1]

array([4, 2])
answered Jan 29, 2023 at 20:24
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.

answered Jan 29, 2023 at 20:22
2
  • I think your example is more insightful for OP. +1 Commented Jan 29, 2023 at 20:32
  • Thanks @Chrysophylaxs. It's definitely important to know both methods and recognize when you can use slicing vs. when to resort to integer indexing. Commented Jan 29, 2023 at 20:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.