【发布时间】:2018-02-09 09:20:18
【问题描述】:
我想在表中找到与特定索引相对应的值。 例如,这是我的表:
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 的方式”来做到这一点?
【问题讨论】: