y0j0
y0j0

Reputation: 3602

Normalize Numpy matrix rows by their average

I'd like to normalize matrix rows by their average and I wrote this code for it

m = np.matrix(
    [[1,2,3,4,5],
     [2,3,2,5,3],
     [5,5,5,3,2]])

for row in m[:,]:
    average = row.sum() / row.shape[1]
    row = row / average

In for cycle, I divide row with average. But this division doesn't change matrix m. How can I achieve this normalization in the most simplest and smartest way?

Upvotes: 0

Views: 1047

Answers (2)

Divakar
Divakar

Reputation: 221574

For in-situ change in m, you can convert to float datatype (if not already) and then use np.divide, like so -

m = m.astype(float)
np.divide(m,m.mean(1),m)

Sample run -

In [294]: m
Out[294]: 
matrix([[1, 2, 3, 4, 5],
        [2, 3, 2, 5, 3],
        [5, 5, 5, 3, 2]])

In [295]: m = m.astype(float)

In [296]: np.divide(m,m.mean(1),m);

In [297]: m
Out[297]: 
matrix([[ 0.33333333,  0.66666667,  1.        ,  1.33333333,  1.66666667],
        [ 0.66666667,  1.        ,  0.66666667,  1.66666667,  1.        ],
        [ 1.25      ,  1.25      ,  1.25      ,  0.75      ,  0.5       ]])

Upvotes: 1

unutbu
unutbu

Reputation: 879591

Compute the row-wise average, and the compute m/average:

In [36]: average = m.mean(axis=1)

In [37]: average
Out[37]: 
matrix([[ 3.],
        [ 3.],
        [ 4.]])

In [38]: m/average
Out[38]: 
matrix([[ 0.33333333,  0.66666667,  1.        ,  1.33333333,  1.66666667],
        [ 0.66666667,  1.        ,  0.66666667,  1.66666667,  1.        ],
        [ 1.25      ,  1.25      ,  1.25      ,  0.75      ,  0.5       ]])

Note that if your matrix contains NaN values, then you could use np.nanmean(m, axis=1) instead of m.mean(axis=1) to compute the row-wise mean while ignoring NaNs.

Upvotes: 6

Related Questions