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

Summing positive elements of each row of an array in Python

I have an array A. I want to sum all the positive elements of each row of A. I present the current and expected output.

import numpy as np
A=np.array([[0,-2,3],[1,0,6],[7,8,0]])
B1=[]
for i in range(0,len(A)):
    B=np.sum(A[i]>0)
    B1.append(B)
print(B1)

The current output is

[1, 2, 2]

The expected output is

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

[3,7,15]

>Solution :

Use numpy.where to mask the negative values:

np.where(A>0, A, 0).sum(axis=1)

Or the where parameter of numpy.sum:

np.sum(A, axis=1, where=A>0)

Output: array([ 3, 7, 15])

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