[Numpy-discussion] Funky vectorisation question

Stéfan van der Walt stefan@sun.ac...
Wed Apr 29 16:48:11 CDT 2009


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


More information about the Numpy-discussion mailing list