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

Keith Goodman kwgoodman@gmail....
Fri Sep 5 09:52:39 CDT 2008


On Fri, Sep 5, 2008 at 7:32 AM, David Cournapeau
<david@ar.media.kyoto-u.ac.jp> wrote:
> Ludwig wrote:
>> 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?
>
> In this case, it is style: sum(a) really calls a.sum() internally; in
> the second case, you are sure to call numpy sum, and not python sum,
> which is a common mistake of people new to numpy.

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


More information about the Numpy-discussion mailing list