Search code examples
pythonnumpydense-rankrescale

Rescaling 2D numpy array as Dense representation


I have a numpy array . I want rescale the elements in the array, so that the smallest number in array is represented by 1, and largest number in array is represented by the number of unique elements in array.

For example

A=[ [2,8,8],[3,4,5] ]  

would become

[ [1,5,5],[2,3,4] ]

Solution

  • Use np.unique with its return_inverse param -

    np.unique(A, return_inverse=1)[1].reshape(A.shape)+1
    

    Sample run -

    In [10]: A
    Out[10]: 
    array([[2, 8, 8],
           [3, 4, 5]])
    
    In [11]: np.unique(A, return_inverse=1)[1].reshape(A.shape)+1
    Out[11]: 
    array([[1, 5, 5],
           [2, 3, 4]])