Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to normalize a 2-dimensional numpy array in python less verbose?

Given a 3 times 3 numpy array

a = numpy.arange(0,27,3).reshape(3,3)  # array([[ 0,  3,  6], #        [ 9, 12, 15], #        [18, 21, 24]]) 

To normalize the rows of the 2-dimensional array I thought of

row_sums = a.sum(axis=1) # array([ 9, 36, 63]) new_matrix = numpy.zeros((3,3)) for i, (row, row_sum) in enumerate(zip(a, row_sums)):     new_matrix[i,:] = row / row_sum 

There must be a better way, isn't there?

Perhaps to clearify: By normalizing I mean, the sum of the entrys per row must be one. But I think that will be clear to most people.

like image 561
Aufwind Avatar asked Jan 18 '12 03:01

Aufwind


1 Answers

Broadcasting is really good for this:

row_sums = a.sum(axis=1) new_matrix = a / row_sums[:, numpy.newaxis] 

row_sums[:, numpy.newaxis] reshapes row_sums from being (3,) to being (3, 1). When you do a / b, a and b are broadcast against each other.

You can learn more about broadcasting here or even better here.

like image 103
Bi Rico Avatar answered Oct 07 '22 01:10

Bi Rico