Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding elements of each row to another array in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.        ]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading