8

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.

2 Answers 2

9

you can create the index tuple first:

index = (numpy.s_[:],)+t 
x[index]
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, thanks for the help (you too, wim). I found more examples for s_ and slice at scipy. I think I looked through that list before, but didn't see anything that looked relevant.
4

HYRY solution is correct, but I have always found numpy's r_, c_ and s_ index tricks to be a bit strange looking. So here is the equivalent thing using a slice object:

x[(slice(None),) + t]

That single argument to slice is the stop position (i.e. None meaning all in the same way that x[:] is equivalent to x[None:None])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.