Home > Software design >  Adding elements of each row to another array in Python
Adding elements of each row to another array in Python

Time:04-11

I have two arrays, Result and X. I would like to add non-zero row elements of Result to each element of X. The desired output is attached.

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])

Desired output:

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.        ]])

CodePudding user response:

One option is to use numpy.where to check if a value in Result is 0 or not and add accordingly:

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

Output:

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.        ]])

CodePudding user response:

You should accept enke's answer, but here's another way of doing it using np.repeat:

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

I think the effect of None and np.newaxis is the same in this context vs the other answer.

  • Related