Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a numpy array like a table

Tags:

python

I have a list

[[0, 3], [5, 1], [2, 1], [4, 5]]

which I have made into an array using numpy.array:

[[0 3]
 [5 1]
 [2 1]
 [4 5]]

How do I sort this like a table? In particular, I want to sort by the second column in ascending order and then resolve any ties by having the first column sorted in ascending order. Thus I desire:

[[2 1]
 [5 1]
 [0 3]
 [4 5]]

Any help would be greatly appreciated!

like image 874
Derek Avatar asked Nov 16 '11 14:11

Derek


2 Answers

See http://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html#numpy.lexsort

Specifically in your case,

import numpy as np
x = np.array([[0,3],[5,1],[2,1],[4,5]])
x[np.lexsort((x[:,0],x[:,1]))]

outputs

array([[2,1],[5,1],[0,3],[4,5]])
like image 110
Andrew Marshall Avatar answered Oct 03 '22 15:10

Andrew Marshall


You can use numpy.lexsort():

>>> a = numpy.array([[0, 3], [5, 1], [2, 1], [4, 5]])
>>> a[numpy.lexsort(a.T)]
array([[2, 1],
       [5, 1],
       [0, 3],
       [4, 5]])
like image 38
Sven Marnach Avatar answered Oct 03 '22 14:10

Sven Marnach