a = np.array([[0, 2, 0, 0], [0, 1, 3, 0], [0, 0, 10, 11], [0, 0, 1, 7]])
array([[ 0, 2, 0, 0],
[ 0, 1, 3, 0],
[ 0, 0, 10, 11],
[ 0, 0, 1, 7]])
每行有 0
个条目。我需要为每个零条目分配一个值,该值的计算如下:
V = 0.1 * Si / Ni
where Si is the sum of row i
Ni is the number of zero entries in row i
我可以相当容易地计算 Si 和 Ni:
S = np.sum(a, axis=1)
array([ 2, 4, 21, 8])
N = np.count_nonzero(a == 0, axis=1)
array([3, 2, 2, 2])
现在,V
计算如下:
V = 0.1 * S/N
array([0.06666667, 0.2 , 1.05 , 0.4 ])
但是如何将 V[i] 分配给第 i 行中的零条目?所以我期望得到以下数组a
:
array([[ 0.06666667, 2, 0.06666667, 0.06666667],
[ 0.2, 1, 3, 0.2],
[ 1.05, 1.05, 10, 11],
[ 0.4, 0.4, 1, 7]])
我需要某种选择性广播操作或分配?
最佳答案
使用 np.where
np.where(a == 0, v.reshape(-1, 1), a)
array([[ 0.06666667, 2. , 0.06666667, 0.06666667],
[ 0.2 , 1. , 3. , 0.2 ],
[ 1.05 , 1.05 , 10. , 11. ],
[ 0.4 , 0.4 , 1. , 7. ]])
关于python - 有选择地设置 numpy 数组中的值(或根据条件设置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60211047/