Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to get values of an array at certain index positions?

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] 
like image 838
MoTSCHIGGE Avatar asked Aug 08 '14 10:08

MoTSCHIGGE


People also ask

How do you extract a value from an array in Python?

You can use the pop() method to remove an element from the array.

How do you access the index of an array element in Python?

We can access elements of an array using the index operator [] . All you need do in order to access a particular element is to call the array you created. Beside the array is the index [] operator, which will have the value of the particular element's index position from a given array.

How do you find the position of an element in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


1 Answers

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]) 
like image 120
Padraic Cunningham Avatar answered Sep 17 '22 01:09

Padraic Cunningham