I have the following numpy matrix:
我有以下numpy矩阵:
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?
是否有一般情况可以处理任何数量的元素而不诉诸循环?
1 个解决方案
#1
3
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
#1
3
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