2

I have a problem accessing the data in a multidimensional numpy-array with python 2.7. The goal is to read multiple values whose positions are stored in a list.

import numpy as np
matrix=np.ones((10,30,5))

positions=[]
positions.append([1,2,3])
positions.append([4,5,6])

for i in positions:
    print matrix[i]

What I want is:

print matrix[1,2,3]

But I get:

print [matrix[1], matrix[2], matrix[3]]

Could you please give me a hint for the correct indexing? Thanks!

1 Answer 1

5

From indexing docs:

In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2,..., expN]; the latter is just syntactic sugar for the former.

So, instead of passing it a list, pass a tuple to matrix:

for i in positions:
    print matrix[tuple(i)]

Lists are used for picking item at particular indices, i.e index arrays:

>>> arr = np.random.rand(10)
>>> arr
array([ 0.56854322,  0.21189256,  0.72516831,  0.85751778,  0.29589961,
        0.90989207,  0.26840669,  0.02999548,  0.65572606,  0.49436744])
>>> arr[[0, 0, 5, 1, 5]]
array([ 0.56854322,  0.56854322,  0.90989207,  0.21189256,  0.90989207])
Sign up to request clarification or add additional context in comments.

2 Comments

First answer after 4 minutes. I was sure it's a simple question, but just couldn't the solution. It's something that's missing in the Scipy docs. Thank you Ashwini!
@Kaioto They have covered it here: docs.scipy.org/doc/numpy/reference/… The NumPy's tentative tutorial is down at the moment for me, so possibly there as well.

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.