简体   繁体   中英

Normalise elements by row in a Numpy array

I have the following numpy matrix:

A = [[a,b,c],
     [d,e,f],
     ...]

I need to zero normalise along the rows (innermost dimension). So the answer needs to be:

B = [[a-(a+b+c)/3, b-(a+b+c)/3, c-(a+b+c)/3],
     [d-(d+e+f)/3, e-(d+e+f)/3, f-(d+e+f)/3],
     ...]

(like finding the mean for each row and subtracting if from each element in the row.)

The number of elements in each row can vary.

Is there a general case that will cope with any number of elements without resorting to looping?

Here's one approach leveraging broadcasting -

A - A.mean(axis=1,keepdims=1)

Sample run -

In [23]: A
Out[23]: 
array([[1, 6, 8],
       [3, 1, 6],
       [6, 2, 4],
       [7, 7, 2]])

In [24]: A - A.mean(axis=1,keepdims=1)
Out[24]: 
array([[-4.        ,  1.        ,  3.        ],
       [-0.33333333, -2.33333333,  2.66666667],
       [ 2.        , -2.        ,  0.        ],
       [ 1.66666667,  1.66666667, -3.33333333]])

In [25]: 1 - (1+6+8)/3.0
Out[25]: -4.0

In [26]: 6 - (1+6+8)/3.0
Out[26]: 1.0

In [28]: 8 - (1+6+8)/3.0
Out[28]: 3.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM