元组多维数组的索引

元组多维数组的索引

本文介绍了元组多维数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我的一个非常类似的问题,但不完全一样。
这其中:here
然而,在ntimes的情况下,数组的大小相匹配的尺寸元组点的数量。
在我来说,我有一个4维数组和二维元组,就像这样:

I found a very similar question to mine, but not exactly the same.This one: hereHowever in ntimes's case the size of the array matches the number of the dimensions the tuple is point at.In my case I have a 4-dimensional array and a 2-dimensional tuple, just like this:

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]

不过,我获得与指数= 2的第一个维度的重复,沿着第四维(因为它在技术上并没有被索引)。这是因为这个索引是除preting双索引的第一尺寸,而不是一个值对每个维,

However, I obtain a repetition of the first dimension with index=2, along the fourth dimension( since it technically hasn't been indexed). 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!

推荐答案

您还可以通过在你的第一个元组单独获得感兴趣的片,然后再建立索引seprately:

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

这可能是一些用户稍微更具可读性,但除此之外,我对mgilson的解决方案倾斜。

That may be slightly more readable for some users, but otherwise I'd lean towards mgilson's solution.

这篇关于元组多维数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:50