I have some data in one array that I want to map into another array, given an array of correspondences:
originaldata is a numpy 2D array,targetdata is another numpy 2D array,mapping is an array that maps between positions, so mapping[x,y] gives me a pair of coordinates of where the data of targetdata[x,y] comes from in originaldata.So far I do something like this:
for (x,y) in ALLTHEPOINTS:
targetdata[x,y]=originaldata[mapping[x,y][0],mapping[x,y][1]]
...which I suspect is very inefficient.
Is there any way to vectorize this? Or is there any numpy function that addresses this type of operation?
This is what fancy indexing is there for:
targetdata = originaldata[mapping[..., 0], mapping[..., 1]]
As a simple example:
>>> original_data = np.arange(6).reshape(2, 3)
>>> original_data
array([[0, 1, 2],
[3, 4, 5]])
>>> mapping = np.array([[[1,0], [1, 1], [1, 2]], # swap rows and reverse
... [[0, 2], [0, 1], [0, 0]]]) # the second one
>>> original_data[mapping[..., 0], mapping[..., 1]]
array([[3, 4, 5],
[2, 1, 0]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With