首页 > 解决方案 > 给定索引数组(i1,i2,...),获取 numpy 嵌套数组中的第 i 个元素

问题描述

给定x一个 numpy 数组:

>>> x
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

还有另一个数组/索引列表:

>>> indices = [2, 1, 1]

是否有一个将两者都作为输入的 numpy 方法:

>>> np.some_method(x, indices, axis=1)

并返回:

array([ 3,  6, 10])  # for the given indices (2, 1, 1) respectively

标签: pythonnumpy

解决方案


正如评论中提到的@Dani,您可以使用高级索引:

x[np.arange(3), indices]

推荐阅读