Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements from an array using another array as index

Say I have an array

A = array([[1,2,3],
           [4,5,6],
           [7,8,9]])

Index array is

B = array([[1], # want [0, 1] element of A
           [0],  # want [1, 0], element of A
           [1]])  # want [2, 1] elemtn of A

By this index array B, I want a 3-by-1 array, whose elements are taken from array A, that is

C = array([[2],
           [4],
           [8]])

I tried numpy.choose, but I failed to that.

like image 947
Alcott Avatar asked Dec 26 '22 06:12

Alcott


1 Answers

For answer completeness... Fancy indexing arrays are broadcast to a common shape, so the following also works, and spares you that final reshape:

>>> A[np.arange(3)[:, None], B]
array([[2],
       [4],
       [8]])
like image 128
Jaime Avatar answered Dec 28 '22 14:12

Jaime