Home > Back-end >  Elements corresponding to indices in Python
Elements corresponding to indices in Python

Time:05-03

I would like to obtain the array elements corresponding to specific indices. The desired output is attached.

import numpy as np
A=np.array([[1.1, 2.3, 1.9],[7.9,4.9,1.4],[2.5,8.9,2.3]])
Indices=np.array([[0,1],[1,2],[2,0]])

The desired output is

array([[2.3],[1.4],[2.5]])

CodePudding user response:

You can use the columns of Indices separately. The first column for the row indices and the second for the column indices:

out = A[Indices[:, [0]], Indices[:, [1]]]

Output:

array([[2.3],
       [1.4],
       [2.5]])

CodePudding user response:

First loop through Indices to get the row and column index i.e. i0 and i1 respectively and then get the value in A. Use this:

output = np.array([[A[i0][i1]] for i0, i1 in Indices])

Output:

array([[2.3],
   [1.4],
   [2.5]])
  • Related