Ste*_*ter 47 python numpy multidimensional-array
如何将numpy数组行除以此行中所有值的总和?
这是一个例子.但我非常确定有一种奇特且更有效的方法:
import numpy as np
e = np.array([[0., 1.],[2., 4.],[1., 5.]])
for row in xrange(e.shape[0]):
e[row] /= np.sum(e[row])
Run Code Online (Sandbox Code Playgroud)
结果:
array([[ 0. , 1. ],
[ 0.33333333, 0.66666667],
[ 0.16666667, 0.83333333]])
Run Code Online (Sandbox Code Playgroud)
DSM*_*DSM 84
方法#1:使用None
(或np.newaxis
)添加额外的维度,以便广播表现如下:
>>> e
array([[ 0., 1.],
[ 2., 4.],
[ 1., 5.]])
>>> e/e.sum(axis=1)[:,None]
array([[ 0. , 1. ],
[ 0.33333333, 0.66666667],
[ 0.16666667, 0.83333333]])
Run Code Online (Sandbox Code Playgroud)
方法#2:go transpose-happy:
>>> (e.T/e.sum(axis=1)).T
array([[ 0. , 1. ],
[ 0.33333333, 0.66666667],
[ 0.16666667, 0.83333333]])
Run Code Online (Sandbox Code Playgroud)
(axis=
如果需要,您可以删除部分以获得简洁.)
方法#3 :(从Jaime的评论中提升)
使用keepdims
参数on sum
来保留维度:
>>> e/e.sum(axis=1, keepdims=True)
array([[ 0. , 1. ],
[ 0.33333333, 0.66666667],
[ 0.16666667, 0.83333333]])
Run Code Online (Sandbox Code Playgroud)
这里,E
是您的原始矩阵,D
是一个对角矩阵,其中每个条目是相应行的总和E
.如果你有幸拥有一个可逆的东西D
,这是一种非常方便的数学方法.
在numpy:
import numpy as np
diagonal_entries = [sum(e[row]) for row in range(e.shape[0])]
D = np.diag(diagonal_entries)
D_inv = np.linalg.inv(D)
e = np.dot(e, D_inv)
Run Code Online (Sandbox Code Playgroud)