Alex Shroyer
Alex Shroyer

Reputation: 3829

How to get multiple coordinates from 2d array in NumPy

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?

Upvotes: 3

Views: 1029

Answers (1)

user17242583
user17242583

Reputation:

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])

Upvotes: 6

Related Questions