简体   繁体   English

元组作为多维数组的索引

[英]Tuple as index of multidimensional array

I found a very similar question to mine, but not exactly the same. 我发现了一个与我非常相似的问题,但不完全相同。 This one: here However in ntimes's case the size of the array matches the number of the dimensions the tuple is point at. 这一个: 这里但是在ntimes的情况下,数组的大小与元组指向的维度的数量相匹配。 In my case I have a 4-dimensional array and a 2-dimensional tuple, just like this: 在我的情况下,我有一个4维数组和一个二维元组,就像这样:

from numpy.random import rand
big_array=rand(3,3,4,5)
tup=(2,2)

I want to use the tuple as an index to the first two dimensions, and manually index the last two. 我想使用元组作为前两个维度的索引,并手动索引最后两个维度。 Something like: 就像是:

big_array[tup,3,2]

However, I obtain a repetition of the first dimension with index=2, along the fourth dimension( since it technically hasn't been indexed). 但是,我沿着第四维获得了索引= 2的第一维的重复(因为它在技术上没有被索引)。 That is because this indexing is interpreting a double indexing to the first dimension instead of one value for each dimension, 这是因为这个索引将双索引解释为第一维而不是每个维的一个值,

eg. 
| dim 0:(index 2 AND index 2) , dim 1:(index 3), dim 2:(index 2), dim 3:(no index)|
instead of 
|dim 0(index 2), dim 1(index 2), dim 2:(index 3), dim 3:(index 2)|.

How can I 'unpack' this tuple then? 那我怎么能“打开”这个元组呢? Any ideas? 有任何想法吗? thanks! 谢谢!

Since you're using numpy : 既然你正在使用numpy

big_array[tup+(3,2)]

should work. 应该管用。 When you call __getitem__ (via the square brackets), the stuff is passed to __getitem__ as a tuple. 当你调用__getitem__ (通过方括号)时,这些东西作为元组传递给__getitem__ You just need to construct the tuple explicitly here (adding tuples together concatenates into a new tuple) and numpy will do what you want. 你只需要在这里明确地构造tuple (将元组连接在一起形成一个新的元组), numpy将做你想要的。

You can also pass in your first tuple alone to get the slice of interest, then index it seprately: 你也可以单独传递你的第一个元组来获得感兴趣的切片,然后分别编入索引:

from numpy.random import rand
big_array=rand(3,3,4,5)
chosen_slice = (2,2)

>>> big_array[ chosen_slice ]
array([[ 0.96281602,  0.38296561,  0.59362615,  0.74032818,  0.88169483],
       [ 0.54893771,  0.33640089,  0.53352849,  0.75534718,  0.38815883],
       [ 0.85247424,  0.9441886 ,  0.74682007,  0.87371017,  0.68644639],
       [ 0.52858188,  0.74717948,  0.76120181,  0.08314177,  0.99557654]])

>>> chosen_part = (1,1)

>>> big_array[ chosen_slice ][ chosen_part ]
0.33640088565877657

That may be slightly more readable for some users, but otherwise I'd lean towards mgilson's solution. 对于某些用户而言,这可能稍微更具可读性,但除此之外,我倾向于mgilson的解决方案。

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

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