[Numpy-discussion] sum of positive values in an array

Michael McNeil Forbes mforbes@physics.ubc...
Sun Sep 7 09:35:25 CDT 2008


On Sep 5, 2008, at 8:52 AM, Keith Goodman wrote:

> Here's another difference:
>
>>> a = np.random.randn(100000)
>>> timeit np.sum(a[np.where(a>0)])
> 100 loops, best of 3: 3.44 ms per loop
>>> timeit a[a > 0].sum()
> 100 loops, best of 3: 2.21 ms per loop

Here is an even faster method (but much more ugly!):
0.25ms:  (a.sum() + abs(a).sum())/2
0.34ms:  a[a > 0].sum()
0.55ms:  np.sum(a[np.where(a>0)])

Michael.



More information about the Numpy-discussion mailing list