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


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Valdi_Bo