How to map a 2D numpy array to a 1D array with another 2D array as a map?

So, I have two 2D numpy, arrays datacontaining the actual sample data:

[[12 15  5  0]
 [ 3 11  3  7]
 [ 9  3  5  2]
 [ 4  7  6  8]]

and another, locationcontaining the map, another 2D array of unique non-overlapping int values ​​corresponding to spaces in the new 1D array of the same size as two:

[[ 5  6  9 10]
 [ 4  7  8 11]
 [ 3  2 13 12]
 [ 0  1 14 15]]

The only way I've been able to complete the transfer so far is with a simple loop:

arr = np.zeros(4*4, dtype = int)

for i in range(4):
    for j in range(4):
        mapval = location[i, j]
        arr[mapval] = data[i, j]

What correctly displays [ 4 7 3 9 3 12 15 11 3 5 0 7 2 5 6 8]

This is good with a simple 4 * 4 array, but the actual data set is synchronized to 512 * 512, and this method takes quite a lot of time. So my question is: are there any functions or methods that use the fast processing capabilities of ufuncs / numpy to do this more efficiently?

+4
1

, , argsort:

data.ravel()[location.ravel().argsort()]
# array([ 4,  7,  3,  9,  3, 12, 15, 11,  3,  5,  0,  7,  2,  5,  6,  8])

import numpy as np
data = np.array([[12, 15,  5,  0],
 [ 3, 11,  3,  7],
 [ 9,  3,  5,  2],
 [ 4,  7,  6,  8]])

location = np.array([[ 5,  6,  9, 10],
 [ 4,  7,  8, 11],
 [ 3,  2, 13, 12],
 [ 0,  1, 14, 15]])
+3

Source: https://habr.com/ru/post/1681064/


All Articles