2017-08-31 35 views
0

我想查找对应于特定索引的表中的值。 例如,这是我的表:数组numpy阵列的Python方式(与行索引)

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]]) 

并且在下面的索引的阵列。该数组中的值是my_array的行。 (列未编入索引,和索引的列索引对应于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]]) 

我想计算与对应于所述值中my_array的行索引和值的相同形状的阵列。 这是我的代码:

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.]] 

有没有更“Python的方式”来做到这一点?

回答

3

使用advanced-indexing -

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

如果索引与索引indexes的列表来选择每列一个,使用 -

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