0
votes

I want to find the values in a table that correspond to specific indexes. For example, this is my table:

import numpy as np
my_array = np.array([[0,1,0,1,0,1,0],[1,2,1,2,1,2,1],[4,5,4,3,3,4,5]])

#---------------------------------------------------------------------
#    my_array :     [[0, 1, 0, 1, 0, 1, 0],
#                    [1, 2, 1, 2, 1, 2, 1],
#                    [4, 5, 4, 3, 3, 4, 5]])

And below is an array of indexes. The values in this array are rows of my_array. (The columns are not indexed, and column index of indexes correspond to the first index of my_array.)

indexes = np.array([[0,0,0,0,0],[1,2,1,2,1]])

#---------------------------------------------------------------------
#   indexes :    [[0, 0, 0, 0, 0],
#                 [1, 2, 1, 2, 1]])

I want to compute an array with the same shape of indexes and values corresponding to the values in row of my_array. This is my code:

result = np.zeros(indexes.shape)

for i in range(0, indexes.shape[0]):
     result[i, :] = my_array[indexes[i, :], np.arange(0, indexes.shape[1])]

#---------------------------------------------------------------------
#   Result :    [[ 0.,  1.,  0.,  1.,  0.],
#                [ 1.,  5.,  1.,  3.,  1.]]

Is there a more "pythonic way" to do that?

1

1 Answers

3
votes

Use advanced-indexing -

my_array[indexes, np.arange(indexes.shape[-1])]

If indexing with list of indices indexes to select one per column, use -

my_array[indexes, np.arange(len(indexes))]