[SciPy-user] Again on Sorting Objects

Robert Kern robert.kern@gmail....
Mon Jan 21 11:57:42 CST 2008


Lorenzo Isella wrote:
> Dear All,
> Again I am struggling with objects I have to re-arrange.
> Say you have the array (already sorted):
> 
> [2 3 4 4 4 4 5 6 6 8 8 8  10 10]
> 
> I now would like to find (definitely in a more efficient way than I am
> doing now):
> 1) how many different elements I have in the array (in this case 7:
> 2,3,4,5,6,8,10).
> 2)where each block of identical, repeated elements starts and finishes.
> I.e. I would like to break up the array this way:
> 
> [2 | 3 | 4 4 4 4 | 5 | 6 6 | 8 8 8 | 10 10 |]
> 
> thus getting a list of "right boundaries" of each block of repeated elements.
> I have been playing with sort and argsort, but with no success.

In [15]: from numpy import *

In [16]: a = array([2, 3, 4, 4, 4, 4, 5, 6, 6, 8, 8, 8, 10, 10])

In [17]: u = unique1d(a)

In [18]: u
Out[18]: array([ 2,  3,  4,  5,  6,  8, 10])

In [21]: i = a.searchsorted(u, side='left')

In [22]: i
Out[22]: array([ 0,  1,  2,  6,  7,  9, 12])

In [23]: j = a.searchsorted(u, side='right')

In [24]: j
Out[24]: array([ 1,  2,  6,  7,  9, 12, 14])

In [25]: for ij in zip(i, j):
    ....:     print a[ij[0]:ij[1]]
    ....:
    ....:
[2]
[3]
[4 4 4 4]
[5]
[6 6]
[8 8 8]
[10 10]

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco


More information about the SciPy-user mailing list