3

I have a multidimensional NumPy array:

In [1]: m = np.arange(1,26).reshape((5,5))

In [2]: m
Out[2]:
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])

and another array p = np.asarray([[1,1],[3,3]]). I wanted p to act as a array of indexes for m, i.e.:

m[p]
array([7, 19])

However I get:

In [4]: m[p]
Out[4]:
array([[[ 6,  7,  8,  9, 10],
        [ 6,  7,  8,  9, 10]],

       [[16, 17, 18, 19, 20],
        [16, 17, 18, 19, 20]]])

How can I get the desired slice of m using p?

1
  • Wait... Well... What? Commented Apr 28, 2013 at 8:07

1 Answer 1

4

Numpy is using your array to index the first dimension only. As a general rule, indices for a multidimensional array should be in a tuple. This will get you a little closer to what you want:

>>> m[tuple(p)]
array([9, 9])

But now you are indexing the first dimension twice with 1, and the second twice with 3. To index the first dimension with a 1 and a 3, and then the second with a 1 and a 3 also, you could transpose your array:

>>> m[tuple(p.T)]
array([ 7, 19])
Sign up to request clarification or add additional context in comments.

Comments

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.