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

Summation of inverse of non-zero elements in array using Python

I would like to obtain a new matrix which calculates the sum of inverse of non-zero elements of each row. The desired output is attached.

import numpy as np
A=np.array([[1,2,0],[4,0,6],[0,8,9]])

Desired output:

array([[(1/1) + (1/2),
(1/4)+(1/6),
(1/8)+(1/9)]])

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 :

Run:

result = np.divide(1, A, where=A != 0).sum(1)

The result is:

array([1.5       , 0.41666667, 0.23611111])

Details:

np.divide(1, A, where=A != 0)

computes "conditional" inverse of each element.

Actually 1 / A (for each element) is computed only for elements != 0.

And the last step is to sum this intermediate result by each row.

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