Virginie Virginie - 3 months ago 25
Python Question

Python: extract subarray from collection of 2D coordinates

In Python, I have a large 2D array containing data, and another Mx2 2D array containing a collection of M 2D coordinates of interest, e.g.

coords=[[150, 123], [151, 123], [152, 124], [153, 125]]


I would like to extract the Mx1 array containing the values of the data array at these coordinates (indices) locations. Obviously,
data[coords]
does not work.

I suspect there is an easy way to do that, but stackoverflow failed me up to now. Thanks in advance for your help.

EDIT: An example would be

data=
[[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 2, 1, 0, 0],
[0, 0, 0, 1, 23, 40, 0, 0],
[0, 0, 0, 1, 1, 2, 0, 0],
[0, 0, 3, 2, 0, 0, 0, 0],
[0, 0, 4, 5, 6, 2, 1, 0],
[0, 0, 0, 0, 1, 20, 0, 0],
[0, 0, 0, 3, 1, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]

coords=[[1,4],[2,4],[2,5],[5,3],[6,5]]


and the desired output would be

out=[2,23,40,5,20]

Answer

You could use a list comprehension:

In [73]: [data[i][j] for i,j in coords]
Out[73]: [2, 23, 40, 5, 20]