Summing positive elements of each row of an array in Python

Question:

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

[3,7,15]
Asked By: isaacmodi123

||

Answers:

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

Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.