# [Numpy-discussion] how to do a proper 2 column sort on a 2 dimensional array ??

Robert Kern robert.kern at gmail.com
Tue Jan 19 13:09:09 EST 2010

```On Tue, Jan 19, 2010 at 11:53, robert somerville <somervi8 at telus.net> wrote:
> Hi;
>  i am having trouble trying to sort the rows of a 2 dimensional array by the
> values in the first column .. does anybody know how or have an example of
> how to do this ??? while leaving the remain columns remain relative to the
>
> from numpy import *
>
> a=array( [ [4, 4, 3], [4, 5, 2],  [3, 1, 1] ] )
>
> i would like to generate the output (or get the output ...)
>
> b = [ [3,1,1], [4,4,3], [4,5,2] ]
>
> to be specific the primary sort is on the the first column, and within the
> primary key, i would like to do a seconday sort of the matrix based on 2nd
> column ..

Let's modify your example slightly so I don't make the same mistake I
did on comp.lang.python. Let's make sure that the input data is not
already partially ordered by the second column. All we need to do is
swap the first two rows.

In [9]: a = np.array( [ [4, 5, 2], [4, 4, 3], [3, 1, 1] ] )

In [10]: i = np.lexsort((a[:,1], a[:,0]))

In [11]: b = a[i]

In [12]: b
Out[12]:
array([[3, 1, 1],
[4, 4, 3],
[4, 5, 2]])

Note that in the lexsort() call, the second column comes first. You
can think of the procedure as "sort by the second column, now sort by
the first column; where there are ties in the first column, the order
is left alone from the previous sort on the second column".

--
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

```