[Numpy-discussion] ndarray.count() ?

Robert Kern robert.kern at gmail.com
Thu Sep 7 16:40:24 EDT 2006


Martin Spacek wrote:
> What's the most straightforward way to count, say, the number of 1s or 
> Trues in the array? Or the number of any integer?
> 
> I was surprised to discover recently that there isn't a count() method 
> as there is for Python lists. Sorry if this has been discussed already, 
> but I'm wondering if there's a reason for its absence.

Mostly, it's simply easy enough to implement yourself. Not all one-liners should 
be methods on the array object.

   (a == value).sum()

Of course, there are several different things you might do. You might want to 
have multiple values broadcast across the array. You might want to reduce the 
count along a given axis. You might want to use floating point comparison with a 
tolerance. Putting all of those options into one method reduces the convenience 
of that method. Putting a crippled implementation (i.e. just that one-liner) 
expands the already-enormous API of the ndarray object without much benefit.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco





More information about the NumPy-Discussion mailing list