numpy数组数组的pythonic方法(带行索引)

时间:2017-08-31 12:07:34

标签: python arrays numpy

我想在表中找到与特定索引相对应的值。 例如,这是我的表:

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

是否有更多" pythonic方式"这样做?

1 个答案:

答案 0 :(得分:3)

使用advanced-indexing -

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

如果使用索引列表indexes进行索引以选择每列一个,请使用 -

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