将每一行的元素添加到 Python 中的另一个数组

Adding elements of each row to another array in Python

我有两个数组,ResultX。我想将 Result 的非零行元素添加到 X 的每个元素。附上所需的输出。

import numpy as np
Result=np.array([[ 0.        ,  -2.46421304,  -4.99073939,  -5.79902063,  0.        ],
       [-10.        ,  0.        ,  -4.99073939,  0.        ,  0.        ],
       [-10.        ,  -2.46421304,  0.        ,  -5.79902063,  0.        ],
       [-10.        ,  0.        ,  -4.99073939,  0.        ,  0.        ],
       [ 0.        ,  -2.46421304,  -4.99073939,  -5.79902063,  0.        ]])

X=np.array([10,2.46421304,4.99073939,5.79902063,0])

期望的输出:

array([[ 0.        ,  10-2.46421304,  10-4.99073939,  10-5.79902063,  0.        ],
       [2.46421304-10.        ,  0.        ,  2.46421304-4.99073939,  0.        ,  0.        ],
       [4.99073939-10.        ,  4.99073939-2.46421304,  0.        ,  4.99073939-5.79902063,  0.       ],
       [5.79902063-10.        ,  0.        ,  5.79902063-4.99073939,  0.        ,  0.        ],
       [ 0.        ,  0-2.46421304,  0-4.99073939,  0-5.79902063,  0.        ]])

一个选项是使用 numpy.where 检查 Result 中的值是否为 0 并相应地添加:

out = np.where(Result!=0, X[:, None] + Result, Result)

输出:

array([[ 0.        ,  7.53578696,  5.00926061,  4.20097937,  0.        ],
       [-7.53578696,  0.        , -2.52652635,  0.        ,  0.        ],
       [-5.00926061,  2.52652635,  0.        , -0.80828124,  0.        ],
       [-4.20097937,  0.        ,  0.80828124,  0.        ,  0.        ],
       [ 0.        , -2.46421304, -4.99073939, -5.79902063,  0.        ]])

您应该接受 enke 的回答,但这是使用 np.repeat 的另一种方法:

out = Result + np.repeat(X[:, np.newaxis], 5, axis=1) * (Result != 0)

我认为 Nonenp.newaxis 在这种情况下与其他答案的效果相同。