Search code examples
pythonarraysnumpylookuplookup-tables

How to make a look up table with negative indices/inputs in python?


I have a set of input matrices A with possibly negative elements. I also have a set of mappings from int to int which i wish to apply over A efficiently. Example:

import numpy as np

ind = np.array([-9, -8, -7, -6, -5, -4, -3, -2, -1])
out = np.array([ 1,  2,  3,  4,  5,  6,  7,  8,  9])

# i-th element of ind should return i-th element of out

a = np.array([[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]])
# print(a)
# array([[-1, -2, -3],
#        [-4, -5, -6],
#        [-7, -8, -9]])

# i want output as 
# array([[ 9,  8,  7],
#        [ 6,  5,  4],
#        [ 3,  2,  1]])

Sorry if i couldn't put it precisely. There need not be a function governing transformation from ind to out.

Only thing i could think of right now is making a dict and iterating over all elements of input matrix. But that would be slow. How to do this efficiently ?


Solution

  • We can use np.searchsorted -

    In [43]: out[np.searchsorted(ind,a)]
    Out[43]: 
    array([[9, 8, 7],
           [6, 5, 4],
           [3, 2, 1]])
    

    For a generic case when ind is not necessarily sorted, we need to use sorter arg -

    In [44]: sidx = ind.argsort()
    
    In [45]: out[sidx[np.searchsorted(ind,a,sorter=sidx)]]
    Out[45]: 
    array([[9, 8, 7],
           [6, 5, 4],
           [3, 2, 1]])