From: Charles R H. <cha...@gm...> - 2006-09-07 20:37:11
|
On 9/7/06, Martin Spacek <sc...@ms...> 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 [78]: a = ran.randint(0,2, size=(10,)) In [79]: a Out[79]: array([0, 1, 0, 1, 1, 0, 0, 1, 1, 1]) In [80]: b = sort(a) In [81]: b.searchsorted(1, side='right') - b.searchsorted(1, side='left') Out[81]: 6 Which counts the number of ones in a. I came across a thread in March: > > http://aspn.activestate.com/ASPN/Mail/Message/numpy-discussion/3066460 > > 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 > though. > > 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 > 1.1000000000000001 > >>> a=[1.1, 1.1, 1.2] > >>> a > [1.1000000000000001, 1.1000000000000001, 1.2] > >>> a.count(1.1) > 2 > >>> a.count(1.1000000000000001) > 2 > >>> a.count(1.2) > 1 Well, 1.1 == 1.1000000000000001 and that doesn't change. You probably need to use different precisions to run into problems. Chuck |