2

Imagine that I have a python array like

array = [[2,3,4],[5,6,7],[8,9,10]]

And a list

list = [0,2,1]

I basically want a one liner to extract the indexed elements from the array given by the list

For example, with the given array and list:

result = [2,7,9]

My kneejerk option was

result = array[:, list]

But that did not work

I know that a for cycle should do it, I just want to know if there is some indexing that might do the trick

2 Answers 2

2

Something like this?

In [24]: a
Out[24]: 
array([[ 2,  3,  4],                                                                              
       [ 5,  6,  7],                                                                              
       [ 8,  9, 10]])                                                                             

In [25]: lis
Out[25]: [0, 2, 1]

In [26]: a[np.arange(len(a)), lis]                                                              
Out[26]: array([2, 7, 9])
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, exactly like that, I wonder why would the arange work, but indexing all of them did not.
@Leonpalafox Check out how indexing on multi-dimensional array works: docs.scipy.org/doc/numpy/user/…
0

Use enumerate to create row indices and unzip (zip(*...)) this collection to get the row indices (the range [0, len(list))) and the column indices (lis) :

a[zip(*enumerate(lis))]

Comments

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.