python - Extract subarray from collection of 2D coordinates? -
in python, have large 2d array containing data, , mx2 2d array containing collection of m 2d coordinates of interest, e.g.
coords=[[150, 123], [151, 123], [152, 124], [153, 125]]
i extract mx1 array containing values of data array @ these coordinates (indices) locations. obviously, data[coords]
not work.
i suspect there easy way that, stackoverflow failed me now. in advance help.
edit: example 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 desired output be
out=[2,23,40,5,20]
you use list comprehension:
in [73]: [data[i][j] i,j in coords] out[73]: [2, 23, 40, 5, 20]
the result returned list comprehension equivalent to
result = [] i,j in coords: result.append(data[i][j])
Comments
Post a Comment