0

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 Answer 1

3

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))]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.