[Numpy-discussion] Funky vectorisation question
Dan Goodman
dg.gmane@thesamovar....
Wed Apr 29 16:49:46 CDT 2009
David Warde-Farley wrote:
> On 29-Apr-09, at 5:06 PM, Dan Goodman wrote:
>
>> Here's the problem I want to write vectorised code for. I start with
>> an
>> array of indices, say I=array([0,1,0,2,0,1,4]), and I want to come up
>> with an array C that counts how many times each index has been seen so
>> far if you were counting through the array from the beginning to the
>> end, e.g. for that I, C=array([0,0,1,0,2,1,0]). This is easy enough to
>> do with a C loop, but trickier to do just with numpy. Any ideas?
>
> How about this:
>
> In [28]: I = array([0,1,0,2,0,1,4])
>
> In [29]: C = empty(len(I),dtype=int)
>
> In [30]: for idx in unique(I):
> ....: V = I == idx
> ....: C[V] = arange(len(V))
> ....:
>
> In [31]: C
> Out[31]: array([0, 0, 1, 0, 2, 1, 0])
>
> David
Thanks David, that's nice but unfortunately that Python loop will kill
me. I'm thinking about some simulation code I'm writing where this
operation will be carried out many, many times, with large arrays I. I
figure I need to keep the Python overheads to a fixed cost to get good
performance.
Dan
More information about the Numpy-discussion
mailing list