better way to do this in Numeric
Duncan Smith
buzzard at urubu.freeserve.co.uk
Mon Aug 4 14:44:56 EDT 2003
"Duncan Smith" <buzzard at urubu.freeserve.co.uk> wrote in message
news:bgm930$nce$1 at newsg4.svr.pol.co.uk...
>
> "John Hunter" <jdhunter at ace.bsd.uchicago.edu> wrote in message
> news:mailman.1060008547.3901.python-list at python.org...
> >
> > I have a list of indices and want to assign the number of times an
> > index shows up in the list to an array with the count specified at the
> > index; ie,
> >
> > from Numeric import *
> >
> > a = zeros((10,), Int)
> > ind = [1,1,4,4,4,4,7,7,9,9,9,9,9]
> >
> > for i in ind:
> > a[i] += 1
> >
> > I'm wondering if there is a way to use some combination of Numeric
> > array functions to make this speedy.
> >
> > Thanks,
> > John Hunter
> >
>
> import Numeric
>
> >>> ind = [1,1,4,4,4,4,7,7,9,9,9,9,9]
> >>> res = Numeric.searchsorted(ind, Numeric.arange(10))
> >>> res = Numeric.concatenate([res, [len(ind)]])
> >>> res[1:] - res[:-1]
> array([0, 2, 0, 0, 4, 0, 0, 2, 0, 5])
> >>>
>
> Duncan
>
>
I assumed the list was sorted. If not,
>>> ind = [7,1,9,1,4,4,4,7,9,9,9,4,9]
>>> res = Numeric.searchsorted(Numeric.sort(ind), Numeric.arange(10))
>>> res = Numeric.concatenate([res, [len(ind)]])
>>> res[1:] - res[:-1]
array([0, 2, 0, 0, 4, 0, 0, 2, 0, 5])
>>>
Duncan
More information about the Python-list
mailing list