[Numpy-discussion] Counting array elements
Todd Miller
jmiller at stsci.edu
Thu Oct 21 15:04:04 CDT 2004
On Thu, 2004-10-21 at 14:30, Todd Miller wrote:
> On Thu, 2004-10-21 at 13:55, Stephen Walton wrote:
> > Is there some simple way of counting the number of array elements which
> > satisfy a certain condition? It is easy to do
> >
> > A[A<=1].sum()
> >
> > to sum all the values of A which are less than 1, but there doesn't seem
> > to be a count() method. I tried
> >
> > (A<=1).sum()
> >
> > but this throws an exception at numarray 1.1. If I try
>
> This works now in CVS and will be part of numarray-1.2.
Stephen tried this and it turns out my earlier statement was untrue,
(A<=1).sum() doesn't do anything reasonable, even in CVS. The problem
is that sum() is written (without direct C support) to conserve
storage. As a result, it doesn't do implicit
> Another more
> tedious approach which works for numarray-1.1 is:
>
> (A <= 1).astype('Int32').sum()
>
There's also a prettier approach that works for 1.1 that I forgot about:
(A <= 1).sum('Int32')
> > sum(A<=value)
> >
> > I have to nest multiple sums if A has rank greater than 1, plus the sum
> > overflows if A is large, apparently because boolean gets treated as
> > Int8. (Try A=arange(1024,shape=(32,32));sum(sum(A<=1024)). You get
> > zero.) The following works:
> >
> > array(A<=1024,type=Int32).sum()
> >
> > but is awkward. Am I missing an obvious better alternative? If not,
> > I'm going to file an RFE :-) .
>
> I don't think there's any need for an RFE, provided you're satisfied
> with (A<=1).sum().
>
> Regards,
> Todd
>
>
>
> -------------------------------------------------------
> This SF.net email is sponsored by: IT Product Guide on ITManagersJournal
> Use IT products in your business? Tell us what you think of them. Give us
> Your Opinions, Get Free ThinkGeek Gift Certificates! Click to find out more
> http://productguide.itmanagersjournal.com/guidepromo.tmpl
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at lists.sourceforge.net
> https://lists.sourceforge.net/lists/listinfo/numpy-discussion
--
More information about the Numpy-discussion
mailing list