python - How to extract a list of elements given by their indices from a numpy array efficiently? -


i have multidimensional numpy array , take of elements construct 1 dimensional array. elements need take given indices, example:

inds = [(0,0), (0,1), (1,1), (1,0), (0,2)]  

i solve in straightforward way:

ls = []  i, j in inds:    ls += [a[i,j]] 

it gives desired result. however, have realized solution slow purposes. there possibility same in more efficient way?

numpy arrays can indexed sequences (and, more generally, numpy arrays).

for example, here's array a

in [19]: out[19]:  array([[ 0,  1,  2,  3,  4],        [ 5,  6,  7,  8,  9],        [10, 11, 12, 13, 14]]) 

i , j hold sequences of first , second coordinates of inds array:

in [20]: out[20]: [0, 0, 1, 1, 0]  in [21]: j out[21]: [0, 1, 1, 0, 2] 

you can use these pull corresponding values out of a:

in [22]: a[i, j] out[22]: array([0, 1, 6, 5, 2]) 

if have inds in code, can separate list of tuples i , j using zip:

in [23]: inds out[23]: [(0, 0), (0, 1), (1, 1), (1, 0), (0, 2)]  in [24]: i, j = zip(*inds)  in [25]: out[25]: (0, 0, 1, 1, 0)  in [26]: j out[26]: (0, 1, 1, 0, 2) 

or, if inds array shape (n, 2), so:

in [27]: inds = np.array(inds)  in [28]: inds out[28]:  array([[0, 0],        [0, 1],        [1, 1],        [1, 0],        [0, 2]]) 

you can assign transpose of inds i, j:

in [33]: i, j = inds.t  in [34]: out[34]: array([0, 0, 1, 1, 0])  in [35]: j out[35]: array([0, 1, 1, 0, 2])  in [36]: a[i, j] out[36]: array([0, 1, 6, 5, 2]) 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -