3

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?

4
  • 1
    are you sure about your code? Should it be targetdata[x,y]=originaldata[mapping[x, y, 0],mapping[x, y, 0]]? Commented Oct 29, 2013 at 0:51
  • @BiRico Oh yeah sorry, I'll edit that. I was just writing that by heart... Commented Oct 29, 2013 at 0:52
  • So is mapping a 3d array, ie (X, Y, 2), or is it an array of tuples or something similar? Commented Oct 29, 2013 at 0:55
  • Numpy has a vectorize function, but it's not magic-speed-dust, just a wrapper for some fors. Regardless, it's a good baseline; use it and worry only if profiling says to. Commented Oct 29, 2013 at 1:00

1 Answer 1

6

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]])
Sign up to request clarification or add additional context in comments.

Comments

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.