2

I have

>>> foo = np.zeros((3,3,3))
>>> foo[1,2,1] = 1
>>> idx = 1,2

I would like to get the equivalent of

>>> foo[1,2,:]
array([ 0.,  1.,  0.])

using idx (to iterate through idx) . Both approaches that I tried didn't work out:

>>> foo[idx, :]
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  1.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])
>>> foo[((idx,)+(slice(None),))]
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  1.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

2 Answers 2

5

Use foo[idx]. Read the following to see how I arrived at this.


foo[1,2,:] is effectively:

In [379]: foo[(1,2,slice(None))]
Out[379]: array([ 0.,  1.,  0.])

The Python interpreter converts the 1,2,: to this tuple, and passes it to the foo.__getitem__ method.

So we just have to find the right way of constructing the tuple. One is:

In [380]: tuple(idx)+(slice(None),)
Out[380]: (1, 2, slice(None, None, None))

resulting in:

In [381]: foo[tuple(idx)+(slice(None),)]
Out[381]: array([ 0.,  1.,  0.])

Actually I don't need the tuple call, idx is already a tuple

In [386]: idx
Out[386]: (1, 2)
In [387]: idx+(slice(None),)
Out[387]: (1, 2, slice(None, None, None))

I would need tuple([1,2]) if idx was initialed as a list.

Double actually, the solution is even simpler. Since we are using : for the last dimension, we can omit it. And since idx is tuple, it already indexes the first 2 dimensions.

In [394]: foo[idx]
Out[394]: array([ 0.,  1.,  0.])

This pair of calls may lend some clarity:

In [396]: foo[(1,2)]
Out[396]: array([ 0.,  1.,  0.])
In [397]: foo[[1,2]]
Out[397]: 
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  1.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a generalization of this, say for 1,2, 0:2?
2
>>> foo[idx + (slice(None),)]
array([ 0.,  1.,  0.])

1 Comment

A bit of explanation about tuples and slice objects might help the poster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.