数组的numpy数组的python方法(带行索引)
我想在表中找到对应于特定索引的值。 例如,这是我的表格:数组的numpy数组的python方法(带行索引),python,arrays,numpy,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], #
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_数组中的行。(列没有索引,索引的列索引对应于my_数组的第一个索引。)
我想计算一个数组,其索引和值的形状与我的_数组行中的值相同。
这是我的代码:
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.]]
有没有更“蟒蛇式”的方法呢?使用-
如果使用索引列表索引索引
为每列选择一个,请使用-
my_array[indexes, np.arange(len(indexes))]
使用-
如果使用索引列表索引索引
为每列选择一个,请使用-
my_array[indexes, np.arange(len(indexes))]
my_array[indexes, np.arange(len(indexes))]