2017-08-31 76 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))]