Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

normalize the rows of numpy array based on a custom function

Tags:

python

numpy

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


1 Answers

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

like image 54
mozway Avatar answered Oct 17 '25 09:10

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!