[英]Given the indexes corresponding to each row, get the corresponding elements from a matrix
Given indexes for each row, how to return the corresponding elements in a 2-d matrix?给定每一行的索引,如何返回二维矩阵中的相应元素? For instance, In array of
np.array([[1,2,3,4],[4,5,6,7]])
I expect to see the output [[1,2],[4,5]]
given indxs = np.array([[0,1],[0,1]])
.例如,在
np.array([[1,2,3,4],[4,5,6,7]])
数组中np.array([[1,2,3,4],[4,5,6,7]])
我希望看到输出[[1,2],[4,5]]
给定indxs = np.array([[0,1],[0,1]])
。 Below is what I've tried:以下是我尝试过的:
a= np.array([[1,2,3,4],[4,5,6,7]])
indxs = np.array([[0,1],[0,1]]) #means return the elements located at 0 and 1 for each row
#I tried this, but it returns an array with shape (2, 2, 4)
a[idxs]
The reason you are getting two times your array is that when you do a[[0,1]]
you are selecting the rows 0 and 1 from your array a, which are indeed your entire array.您获得两次数组的原因是,当您执行
a[[0,1]]
您是从数组 a 中选择第 0 行和第 1 行,它们确实是您的整个数组。
In[]: a[[0,1]]
Out[]: array([[1, 2, 3, 4],
[4, 5, 6, 7]])
You can get the desired output using slides.您可以使用幻灯片获得所需的输出。 That would be the easiest way.
那将是最简单的方法。
a = np.array([[1,2,3,4],[4,5,6,7]])
a[:,0:2]
Out []: array([[1, 2],
[4, 5]])
In case you are still interested on indexing, you could also get your output doing:如果您仍然对索引感兴趣,您还可以让您的输出执行以下操作:
In[]: [list(a[[0],[0,1]]),list(a[[1],[0,1]])]
Out[]: [[1, 2], [4, 5]]
The NumPy documentation gives you a really nice overview on how indexes work. NumPy文档为您提供了关于索引如何工作的非常好的概述。
In [120]: indxs = np.array([[0,1],[0,1]])
In [121]: a= np.array([[1,2,3,4],[4,5,6,7]])
...: indxs = np.array([[0,1],[0,1]]) #
You need to provide an index for the first dimension, one that broadcasts with with indxs
.您需要为第一个维度提供索引,该索引与
indxs
一起indxs
。
In [122]: a[np.arange(2)[:,None], indxs]
Out[122]:
array([[1, 2],
[4, 5]])
indxs
is (2,n), so you need a (2,1) array to give a (2,n) result indxs
是 (2,n),所以你需要一个 (2,1) 数组来给出 (2,n) 结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.