'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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source