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

标签 python numpy array-broadcasting

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/

相关文章:

python - QTableWidgetItem.data(self, int *role*) 中的 "role"参数是什么?

python - 相隔 >292 年的日期差值

python - 执行图像减法时退出代码139

python - Numpy 优化 reshape : 2D array to 3D

python - 需要 Numpy 帮助 : how to use boolean values to calculate ranges and add values together within ranges?

python - 将 N 维数组广播到 (N+1) 维数组并对除 1 维之外的所有维求和

python - Numpy函数获取添加数组的形状

python - 访问 ElementTree 节点父节点

python - Flask 猜谜游戏无法正确响应

python - Plotly:如何获取跟踪颜色属性以绘制具有相同颜色的选定标记?