numpy 数组数组的 Pythonic 方式(带有行索引) [英] Pythonic way for numpy array of array (with index of rows)
问题描述
我想在表中查找与特定索引相对应的值.例如,这是我的表:
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?
推荐答案
使用 高级索引
-
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 方式(带有行索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!