1

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] 
1
  • This question is similar to: Sum of negative elements in each column of a NumPy array. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 11, 2024 at 9:56

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

The where parameter version needs an out parameter as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.