[Numpy-discussion] lexsort

Charles R Harris charlesr.harris at gmail.com
Fri Jun 2 01:05:13 EDT 2006


Tom,

The list -- nee tuple, thanks Travis -- is the list of key sequences and
each key sequence can be a column in a matrix. So for instance if you wanted
to sort on a few columns of a matrix, say columns 2,1, and 0, in that order,
and then rearrange the rows so the columns were ordered, you would do
something like:

>>> a = randint(0,2,(7,4))
>>> a
array([[0, 0, 0, 1],
       [0, 0, 1, 0],
       [1, 0, 0, 1],
       [0, 1, 0, 1],
       [1, 1, 1, 0],
       [0, 1, 1, 1],
       [0, 1, 0, 1]])
>>> ind = lexsort((a[:,2],a[:,1],a[:,0]))
>>> sorted = a[ind]
>>> sorted
array([[0, 0, 0, 1],
       [0, 0, 1, 0],
       [0, 1, 0, 1],
       [0, 1, 0, 1],
       [0, 1, 1, 1],
       [1, 0, 0, 1],
       [1, 1, 1, 0]])

Note that the last key defines the major order.

Chuck

On 6/1/06, Tom Denniston <tom.denniston at alum.dartmouth.org> wrote:
>
> This function is really useful but it seems to only take tuples not
> ndarrays.   This seems kinda strange.  Does one have to convert the
> ndarray into a tuple to use it?  This seems extremely inefficient.  Is
> there an efficient way to argsort a 2d array based upon multiple
> columns if lexsort is not the correct way to do this?  The only way I
> have found to do this is to construct a list of tuples and sort them
> using python's list sort.  This is inefficient and convoluted so I was
> hoping lexsort would provide a simple solution.
>
> --Tom
>
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at lists.sourceforge.net
> https://lists.sourceforge.net/lists/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20060601/8f042a6b/attachment-0001.html>


More information about the NumPy-Discussion mailing list