Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

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

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!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Since you're using 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. You just need to construct the tuple explicitly here (adding tuples together concatenates into a new tuple) and numpy will do what you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...