+1 vote
in Programming Languages by (9.6k points)
I want to normalize each row of a matrix by dividing all its elements by the maximum value in the row. What is the Pythonic way to do this?

E.g.

The original matrix is

[[1, 2, 3],

 [4, 5, 6],

 [7, 8, 9]]

The output should be

[[0.33333333, 0.66666667, 1]

 [0.66666667, 0.83333333, 1]

 [0.77777778, 0.88888889, 1]]

1 Answer

+3 votes
by (59.4k points)
selected by
 
Best answer

Here is the code for normalizing each row by diving row elements by the maximum value of the row:

import numpy as np

# numpy array

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

# max value in each row

row_max_values = np.max(aa, axis=1)

# Reshape row_max_values

row_max_values = row_max_values.reshape((-1, 1))

# Divide each row by its maximum value

normalized_aa = aa / row_max_values

The code first finds the maximum value in each row and then reshapes the array to (3, 1) matrix. Then it divides row elements by the maximum value in the row. 


...