[Numpy-discussion] Is there a way that indexing a matrix of data with a matrix of indices?

Sebastian Berg sebastian at sipsolutions.net
Wed Nov 29 12:31:54 EST 2017

On Wed, 2017-11-29 at 14:56 +0000, ZHUO QL (KDr2) wrote:
> Hi, all
> suppose:
> - D, is the data matrix, its shape is  M x N
> - I, is the indices matrix, its shape is M x K,  K<=N
> Is there a efficient way to get a Matrix R with the same shape of I
> so that R[x,y] = D[x, I[x,y]] ?
> A nested for-loop or list-comprehension is too slow for me.  

Advanced indexing can do any odd thing you might want to do. I would
not suggest to use the matrix class, but always use the array class in
case you are doing that though.

This should do the trick, I will refer the the documentation for how it
works, except that it is basically:

R[x,y] = D[I1[x, y], I2[x, y]]

R = D[np.arange(I.shape[0])[:, np.newaxis], I]

- Sebastian

> Thanks.
> ----
> ZHUO QL (KDr2) http://kdr2.com
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at python.org
> https://mail.python.org/mailman/listinfo/numpy-discussion
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 801 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20171129/fa0c8a45/attachment.sig>

More information about the NumPy-Discussion mailing list