[Numpy-discussion] ndarray.count() ?
Charles R Harris
charlesr.harris at gmail.com
Thu Sep 7 15:37:07 CDT 2006
On 9/7/06, Martin Spacek <scipy at mspacek.mm.st> 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.
I don't know about count, but you can gin up something like this
In : a = ran.randint(0,2, size=(10,))
In : a
Out: array([0, 1, 0, 1, 1, 0, 0, 1, 1, 1])
In : b = sort(a)
In : b.searchsorted(1, side='right') - b.searchsorted(1, side='left')
Which counts the number of ones in a.
I came across a thread in March:
> that talked a bit about this in terms of speed, but what about just the
> convenience of having a count() method?
> Looks like masked arrays have a count method, don't know much about them
> Also, I understand the inaccuracies when converting between binary and
> decimal floating point representations, and therefore making counting of
> a specific float value in an array somewhat undefined, yet it seems to
> work in Python lists:
> >>> 1.1
> >>> a=[1.1, 1.1, 1.2]
> >>> a
> [1.1000000000000001, 1.1000000000000001, 1.2]
> >>> a.count(1.1)
> >>> a.count(1.1000000000000001)
> >>> a.count(1.2)
Well, 1.1 == 1.1000000000000001 and that doesn't change. You probably need
to use different precisions to run into problems.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Numpy-discussion