3

I am trying to access a value in a multi dimensional numpy array. This can be easily done when you know everything, for exemple :

T = numpy.arrange(9).reshape(3, 3) T[2, 2]

And it returns 8, which is what I want. Now, Let's assume [2, 2] is stored in index variable. How can I do to take the value in T with the index stored in index ? I would like to do T[index] but it returns the last row twice (pretty logical but not what I want).

Thank you !

2
  • 5
    Try ind=tuple(2,2); x[ind] Commented Feb 8, 2016 at 15:25
  • Thanks, works perfectly ! Commented Feb 8, 2016 at 15:29

1 Answer 1

2

Try

ind=tuple(2,2)
x[ind]

x[2,2] is the same as x[(2,2)] which is translated into a method call: x.__getitem__((2,2)).

Some numpy functions build an index as a list or array, then convert it to a tuple for use in the index.

Sign up to request clarification or add additional context in comments.

1 Comment

If you want to access multiple values at once, make sure to use a 2-tuple which consists of two arrays: first for x-values, second for y-values respectively. If you have a list of indices in format p=[[x0,y0],[x1,y1], ... ] for the 2d array D, just use indx=tuple(np.transpose(p)) which is ([x0,x1,..],[y0,y1,...]) and access via D[indx].

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.