31

I have a numpy array like this:

a = [0,88,26,3,48,85,65,16,97,83,91]

How can I get the values at certain index positions in ONE step? For example:

ind_pos = [1,5,7]

The result should be:

[88,85,16]
1
  • 2
    a is not a numpy array in the question but a simple list Commented Oct 2, 2018 at 9:45

5 Answers 5

36

Just index using you ind_pos

ind_pos = [1,5,7]
print (a[ind_pos]) 
[88 85 16]


In [55]: a = [0,88,26,3,48,85,65,16,97,83,91]

In [56]: import numpy as np

In [57]: arr = np.array(a)

In [58]: ind_pos = [1,5,7]

In [59]: arr[ind_pos]
Out[59]: array([88, 85, 16])
Sign up to request clarification or add additional context in comments.

2 Comments

Ah it has to be a numpy array. If I try it like this, it doesn´t work: a = [0,88,26,3,48,85,65,16,97,83,91] ind_pos = [1,5,7] a[ind_pos] Traceback (most recent call last): File "<ipython-input-121-92d3ce287d9d>", line 1, in <module> a[ind_pos] TypeError: list indices must be integers, not list But if I add the line "arr = np.array(a)", it works. Thanks!
Ah ok, I presumed a was a numpy array. Yes a would need to be a numpy array
24

The one liner "no imports" version

a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]

Comments

8

Although you ask about numpy arrays, you can get the same behavior for regular Python lists by using operator.itemgetter.

>>> from operator import itemgetter
>>> a = [0,88,26,3,48,85,65,16,97,83,91]
>>> ind_pos = [1, 5, 7]
>>> print itemgetter(*ind_pos)(a)
(88, 85, 16)

3 Comments

is this or numpy faster?
It depends. If you already have a NumPy array, that should be faster. If you have to construct a NumPy array from your list first, the time it takes to do that and the selection may be slower than it would be to simply operate on the list.
There really should be a way to do this without having to call in a package
5

You can use index arrays, simply pass your ind_pos as an index argument as below:

a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])

print(a[ind_pos])
# [88,85,16]

Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).

Comments

-2

your code would be

a = [0,88,26,3,48,85,65,16,97,83,91]

ind_pos = [a[1],a[5],a[7]]

print(ind_pos)

you get [88, 85, 16]

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.