Reputation: 3444
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?
Upvotes: 1
Views: 70
Reputation: 221514
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
Upvotes: 3