[Numpy-discussion] Funky vectorisation question
Dan Goodman
dg.gmane@thesamovar....
Wed Apr 29 17:21:16 CDT 2009
Stéfan van der Walt wrote:
> 2009/4/29 Dan Goodman <dg.gmane@thesamovar.net>:
>> 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?
>
> This is not effective memory-wise, but it avoids the for-loop:
>
> np.diag(np.cumsum(x == x[:, None], axis=1)) - 1
>
> Cheers
> Stéfan
That's incredibly ingenious! Kudos! But, as you say, I think the memory
issue will cause me problems here...
Dan
More information about the Numpy-discussion
mailing list