3

I have a matrix A, and a (list of tuples) corresponding to coordinates C. How do I get A[C]?

For example:

>>> A
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> C
[(0,0), (1,2), (4,-1)]

The function I want, but don't know the name of, works like this:

>>> func(A,C)
[0, 7, 24]

Does such a function (or some funky NumPy indexing syntax) exist, or is a for loop the only way to get this result?

1 Answer 1

6

You have a list of X,Y pairs. That can't be fed directly to an arrays indexer - it needs to be changed a bit.

Instead of [(X,Y), (X,Y), (X,Y)], you need [(X,X,X), (Y,Y,Y)]:

>>> x = [x for x,y in C]
>>> y = [y for x,y in C]
>>> A[x, y]
array([ 0,  7, 24])

Or even simpler:

>>> A[tuple(zip(*C))]
array([ 0,  7, 24])
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. The A[tuple(zip(C))] method (without the *) also works when C is another NumPy array (with a shape like (2, x)).

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.