[SOLVED] normalize the rows of numpy array based on a custom function

Issue

I have an numpy array. I want to normalized each rows based on this formula

x_norm = (x-x_min)/(x_max-x_min)

, where x_min is the minimum of each row and x_max is the maximum of each row. Here is a simple example:

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

and desired output:

a = np.array([
          [0, 0.5 ,1],
          [0, 0.4 ,1],
          [0.2, 1 ,0]
    ])

Thank you

Solution

IIUC, you can use raw numpy operations:

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

x_norm = ((x.T-x.min(1))/(x.max(1)-x.min(1))).T
# OR
x_norm = (x-x.min(1)[:,None])/(x.max(1)-x.min(1))[:,None]

output:

array([[0. , 0.5, 1. ],
       [0. , 0.4, 1. ],
       [0.2, 1. , 0. ]])

NB. if efficiency matters, save the result of x.min(1) in a variable as it is used twice

Answered By – mozway

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *