[Numpy-discussion] Finding the same value in List

Todd toddrjen@gmail....
Wed Apr 17 04:02:24 CDT 2013


On Wed, Apr 17, 2013 at 10:46 AM, Todd <toddrjen@gmail.com> wrote:

> x,i=numpy.unique(y, return_inverse=True)
> f=[numpy.where(i==ind) for ind in range(len(x))]
>
>
>

A better version would be (np.where returns tuples, but we don't want
tuples):

x,i=numpy.unique(y, return_inverse=True)
f=[numpy.where(i==ind)[0] for ind in range(len(x))]

You can also do it this way, but it is much harder to read IMO:

x=numpy.unique(y)
f=numpy.split(numpy.argsort(y),
numpy.nonzero(numpy.diff(numpy.sort(y)))[0]+1)

This version figures out the indexes needed to put the values of y in
sorted order (the same order x uses), then splits it into sub-arrays based
on value.  The principle is simpler but the implementation looks like clear
to me.

Note that these are only guaranteed to work on 1D arrays, I have not tested
them on multidimensional arrays
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20130417/bae45754/attachment.html 


More information about the NumPy-Discussion mailing list