[Numpy-discussion] how to do a proper 2 column sort on a 2 dimensional array ??
Tue Jan 19 12:09:09 CST 2010
On Tue, Jan 19, 2010 at 11:53, robert somerville <email@example.com> wrote:
> 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
> leading column
> 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 : a = np.array( [ [4, 5, 2], [4, 4, 3], [3, 1, 1] ] )
In : i = np.lexsort((a[:,1], a[:,0]))
In : b = a[i]
In : b
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".
"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 NumPy-Discussion