Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy multidimensional array slicing

Suppose I have defined a 3x3x3 numpy array with

x = numpy.arange(27).reshape((3, 3, 3))

Now, I can get an array containing the (0,1) element of each 3x3 subarray with x[:, 0, 1], which returns array([ 1, 10, 19]). What if I have a tuple (m,n) and want to retrieve the (m,n) element of each subarray(0,1) stored in a tuple?

For example, suppose that I have t = (0, 1). I tried x[:, t], but it doesn't have the right behaviour - it returns rows 0 and 1 of each subarray. The simplest solution I have found is

x.transpose()[tuple(reversed(t))].transpose()

but I am sure there must be a better way. Of course, in this case, I could do x[:, t[0], t[1]], but that can't be generalised to the case where I don't know how many dimensions x and t have.

like image 475
James Avatar asked Sep 06 '11 22:09

James


1 Answers

you can create the index tuple first:

index = (numpy.s_[:],)+t 
x[index]
like image 116
HYRY Avatar answered Sep 19 '22 18:09

HYRY