在 numpy 数组中有选择地设置值(或根据条件设置)
Selectively set values in numpy array (or set on condition)
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 行中的 zero 条目?所以我希望得到以下数组 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
的方法:
z = a == 0
np.where(z, (0.1*a.sum(1)/z.sum(1))[:,None], 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. ]])
也许使用面具:
for i in range(V.size):
print((a[i,:] == 0) * V[i] + a[i,:])
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 行中的 zero 条目?所以我希望得到以下数组 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
的方法:
z = a == 0
np.where(z, (0.1*a.sum(1)/z.sum(1))[:,None], 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. ]])
也许使用面具:
for i in range(V.size):
print((a[i,:] == 0) * V[i] + a[i,:])