Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

python - Numpy 2d array - take N elements from specified index

Assuming I have a 2d numpy array:

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. 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].

The final output should be:

[[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.

Any help would be appreciated!

question from:https://stackoverflow.com/questions/65921824/numpy-2d-array-take-n-elements-from-specified-index

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 Noneor something. Then create a 2d index array from the vec by adding sequential integers from 0 and simply index the original matrix.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...