问题描述
我想在表中找到与特定索引相对应的值.例如,这是我的桌子:
I want to find the values in a table that correspond to specific indexes.For example, this is my table:
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的第一个索引.)
And below is an array of indexes. The values in this array are rows of my_array. (The columns are not indexed, and column index of indexes correspond to the first index of 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行中的值相对应.这是我的代码:
I want to compute an array with the same shape of indexes and values corresponding to the values in row of my_array.This is my code:
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方式"可以做到这一点吗?
Is there a more "pythonic way" to do that?
推荐答案
使用 advanced-indexing
-
my_array[indexes, np.arange(indexes.shape[-1])]
如果使用索引列表indexes
进行索引以每列选择一个索引,请使用-
If indexing with list of indices indexes
to select one per column, use -
my_array[indexes, np.arange(len(indexes))]
这篇关于数组(带有行索引)的numpy数组的Pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!