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

Ludwig ludwigbrinckmann@gmail....
Fri Sep 5 09:45:57 CDT 2008


What are the relative merits of
sum(a[where(a>0])

to

a[a > 0].sum()

?
Second one is more OO, takes a few keystrokes less to type. Is there any
real difference if it came to very large arrays? Or is it 'just' a style
question?

Ludwig


2008/9/5 Zachary Pincus <zachary.pincus@yale.edu>

> >
> > Hi, probably a basic question, but I'm looking for a neat way to sum
> > all the positive values in an array of floats.  I'm currently doing it
> > the hard way, but am hoping there is some cunning and elegant syntax I
> > can use instead
>
> Fancy indexing's my favorite cunning and elegant syntax:
>
> a = numpy.random.randn(100)
> a.sum()
> a > 0 # gives a boolean array that's True where the elements of a are
>  > 0.
> a[a > 0] # retrieve from a only the elements with True in the boolean
> array.
> a[a > 0].sum() # your desired result.
>
> Note that you can also fancy-index with a list/array of indices, as
> well as a boolean "mask" array:
> a[[1, 40, 55]] # pulls just the values at index 1, 40, and 55 out of a
> into a shape (3,) array.
>
> Zach
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20080905/59a6dc73/attachment.html 


More information about the Numpy-discussion mailing list