在numpy数组中有选择地设置值(或根据条件设置)

问题描述 投票:2回答:2
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]])

我需要某种选择性的广播操作或分配吗?

python numpy numpy-broadcasting
2个回答
0
投票

这是使用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.        ]])

0
投票

使用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.        ]])
© www.soinside.com 2019 - 2024. All rights reserved.