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)]])
CodePudding user response:
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.