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

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


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 npIn [57]: arr = np.array(a)In [58]: ind_pos = [1,5,7]In [59]: arr[ind_pos]Out[59]: array([88, 85, 16])


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 ]


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)