Map NumPy Values

Viewed 71

Let's say I have a NumPy array:

x = np.array([[0, 5],
              [1, 6],
              [4, 3],
              [2, 4],
              [3, 2]])

and a "look-up" array that tells me how to map one integer (first column) to another (second column):

lookup = np.array([[0, 50],
                   [1, 16],
                   [2, 47],

So, 0 -> 50, 1 -> 16, and 2 -> 47. Notice that integers [3, 4, 5, 6] is not in the lookup and therefore do not need to be changed. A simple way to do this is:

for i in range(lookup.shape[0]):
    num = lookup[i, 0]
    x[x == num] = lookup[i, 1]

And the expected output should be:

np.array([[50, 5],
          [16, 6],
          [4, 3],
          [47, 4],
          [3, 47]])

For a big 2D array x and a much larger lookup, is there a more efficient way to do this in a vectorized way in NumPy?

2 Answers

My approach for the case where x does not contain negative or big integers:

a = np.arange(x.max()+1)

a[lookup[:,0]] = lookup[:,1]

x = a[x]

Hope this helps!

x = np.array([[0, 5],
              [1, 6],
              [4, 3],
              [2, 4],
              [3, 2]])

lookup = np.array([[0, 50],
                   [1, 16],

                   [2, 47]])

# building a dictionary
lookup = {each[0]:each[1] for each in lookup}

vfunc = np.vectorize(lambda x: lookup.get(x, x))

vfunc(x) # gives your result

output

array([[50,  5],
       [16,  6],
       [ 4,  3],
       [47,  4],
       [ 3, 47]])
Related