[Numpy-discussion] Counting array elements

Todd Miller jmiller at stsci.edu
Thu Oct 21 11:33:46 CDT 2004


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.  Another more
tedious approach which works for numarray-1.1 is:

(A <= 1).astype('Int32').sum()

> 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





More information about the Numpy-discussion mailing list