简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM