简体   繁体   English

多维数组的索引

[英]Index of multidimensional array

I have a problem using multi-dimensional vectors as indices for multi-dimensional vectors. 我在使用多维矢量作为多维矢量的索引时遇到问题。 Say I have C.ndim == idx.shape[0], then I want C[idx] to give me a single element. 假设我有C.ndim == idx.shape [0],那么我想让C [idx]给我一个元素。 Allow me to explain with a simple example: 让我用一个简单的例子来解释:

A = arange(0,10)
B = 10+A
C = array([A.T, B.T])
C = C.T
idx = array([3,1])

Now, C[3] gives me the third row, and C[1] gives me the first row. 现在,C [3]给我第三行,C [1]给我第一行。 C[idx] then will give me a vstack of both rows. C [idx]然后会给我两行的vstack。 However, I need to get C[3,1]. 但是,我需要获取C [3,1]。 How would I achieve that given arrays C, idx? 我将如何实现给定的数组C,idx?

/edit: An answer suggested tuple(idx). /编辑:一个答案建议元组(idx)。 This work's perfectly for a single idx. 这项工作非常适合单个idx。 But: Let's take it to the next level: say INDICES is a vector where I have stacked vertically arrays of shape idx. 但是:让我们更上一层楼:说INDICES是一个向量,其中我垂直堆叠了idx形状的数组。 tuple(INDICES) will give me one long tuple, so C[tuple(INDICES)] won't work. tuple(INDICES)将给我一个长元组,因此C [tuple(INDICES)]将不起作用。 Is there a clean way of doing this or will I need to iterate over the rows? 有没有一种干净的方法可以执行此操作,或者我需要遍历行?

If you convert idx to a tuple , it'll be interpreted as basic and not advanced indexing: 如果将idx转换为tuple ,它将被解释为基本索引而不是高级索引:

>>> C[3,1]
13
>>> C[tuple(idx)]
13

For the vector case: 对于矢量情况:

>>> idx
array([[3, 1],
       [7, 0]])
>>> C[3,1], C[7,0]
(13, 7)
>>> C[tuple(idx.T)]
array([13,  7])
>>> C[idx[:,0], idx[:,1]]
array([13,  7])

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

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