简体   繁体   English

Numpy 二维数组 - 从指定索引中获取 N 个元素

[英]Numpy 2d array - take N elements from specified index

Assuming I have a 2d numpy array:假设我有一个 2d numpy 阵列:

mat=[[5,5,3,6,3],
     [3,2,7,8,1],
     [7,5,5,2,0]]

and a vector of indexes:和一个索引向量:

vec=[3,1,2]

What I need is to take 3 elements from the corresponding index.我需要的是从相应的索引中取 3 个元素。 For example the first element in the vector, that corresponds to the first line in the matrix is 3. Thus I need to take 3 elements from index 3 (0-based) in the first line, which is 6. So what I need is [6,3,None] .例如,向量中的第一个元素,对应于矩阵中的第一行是 3。因此我需要从第一行的索引 3(从 0 开始)中取 3 个元素,即 6。所以我需要的是[6,3,None]

The final output should be:最终的 output 应该是:

[[6,3,None],
 [2,7,8],
 [5,2,0]]

I tried to play with take and with fancy indexing, but couldn't get the desired output.我尝试使用take和花哨的索引,但无法获得所需的 output。

Any help would be appreciated!任何帮助,将不胜感激!

You can do this -你可以这样做 -

import numpy as np

mat=np.array([[5,5,3,6,3],
            [3,2,7,8,1],
            [7,5,5,2,0]])

mat = np.hstack((mat, np.ones((3,3))*np.nan))

vec=np.array([3,1,2])
idx = vec[:, None] + np.arange(0, 3)
print(mat[np.arange(3)[:,None], idx])

Gives -给 -

[[ 6.  3. nan]
 [ 2.  7.  8.]
 [ 5.  2.  0.]]

First just append the original array with three columns of inf or None or something.首先只是 append 具有三列infNone或其他东西的原始数组。 Then create a 2d index array from the vec by adding sequential integers from 0 and simply index the original matrix.然后通过添加从 0 开始的连续整数从vec创建一个二维索引数组,并简单地索引原始矩阵。

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

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