简体   繁体   中英

Mix two NumPy arrays to one with look-up-table behavior

I have the following problem: I would like to mix two arrays in Python, using NumPy. I made a small example below to show, what I would like to have.

arr1 = np.array([0,1,2,1,0,2])

What I would like to do, is to use an arr2 as a lookup-table, which assigns output values based on given input values, according to the correlation in arr2.

arr2 = np.array([[0,1,2,5,6],
                 [7,6,4,8,2]])

So the matching from the "lookup-table" arr2 is:

0 --> 7
1 --> 6
2 --> 4
5 --> 8
6 --> 2

Edit: The first row of arr2 is always increasing, but without constant step size.

In the end, I would like to apply this lookup-table to my given input array arr1. This means, my goal is, to get:

arr3 = np.array([[0,1,2,1,0,2],
                 [7,6,4,6,7,4]])

It is important, that arr1 has any arbitrary length, while arr2 has only the minimal necessary length, to directly assign an input value to an output value.

Is there any very efficient way using NumPy, to do this matching without using a normal for loop, which iterates over all values?

Thank you in advance.

Having the array already sorted and with unique values makes it a bit simpler.

_, x_idx = np.unique(arr1, return_inverse=True)
np.take(arr2[1,:], x_idx) #or
arr2[1,:][x_idx]

This finds the index of the values in your lookuptable in x_idx and then uses fancy indexing to apply the lookup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM