SUM only of positive numbers from array

Peter Otten __peter__ at web.de
Fri Jan 8 03:17:42 EST 2016


Davorin Bajic wrote:

> Hi All,
> 
> I should help...
> 
> I want to calculate the sum of a positive number, for each row:
> 
> 
> x = ((mat_1 / s_1T)-(s_2 / total))
> y = (np.sum(x > 0, axis=1)).reshape(-1, 1).tolist()
> 
> However, this part of the code only calculation count, I need sum.
> 
> Any ideas how to solve this problem?

Use x>0 as "index":

>>> import numpy
>>> x = numpy.array([1, -2, 3])
>>> x>0
array([ True, False,  True], dtype=bool)
>>> x[x>0]
array([1, 3])
>>> x[x>0].sum()
4




More information about the Python-list mailing list