简体   繁体   English

numpy,按一维索引数组选择行中的元素

[英]numpy, Select elements in rows by 1d indexes array

Let we have square array, n*n.让我们有方阵,n*n。 For example, n=3 and array is this:例如,n=3,数组是这样的:

arr = array([[0, 1, 2],
   [3, 4, 5],
   [6, 7, 8]])

And let we have array of indices in the each ROW.让我们在每个 ROW 中都有索引数组。 For example:例如:

myidx=array([1, 2, 1], dtype=int64)

I want to get:我想得到:

[1, 5, 7] [1, 5, 7]

Because in line [0,1,2] take element with index 1, in line [3,4,5] get element with index 2, in line [6,7,8] get element with index 1.因为在第 [0,1,2] 行获取索引为 1 的元素,在第 [3,4,5] 行获取索引为 2 的元素,在第 [6,7,8] 行获取索引为 1 的元素。

I'm confused, and can't take elements this way using standard numpy indexing.我很困惑,不能使用标准的 numpy 索引以这种方式获取元素。 Thank you for answer.谢谢你的答案。

There's no real pretty way but this does what you are looking for :)没有真正漂亮的方法,但这可以满足您的要求:)

In [1]: from numpy import *

In [2]: arr = array([[0, 1, 2],
   [3, 4, 5],
   [6, 7, 8]])

In [3]: myidx = array([1, 2, 1], dtype=int64)

In [4]: arr[arange(len(myidx)), myidx]
Out[4]: array([1, 5, 7])

达到目标的更简单方法是使用选择numpy 函数:

numpy.choose(myidx, arr.transpose())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM