Sort numpy array like table

I have a list

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

which I did in an array using numpy.array:

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

How to sort this as a table? In particular, I want to sort by the second column in ascending order and then resolve any relationships, having the first column sorted in ascending order. Therefore, I wish:

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

Any help would be greatly appreciated!

+5
source share
4 answers

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

In particular, 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]))]

exits

array([[2,1],[5,1],[0,3],[4,5]])
+7
source

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]])
+4
source

- , , argsort, :

a = np.array([[0, 3], [5, 1], [2, 1], [4, 5]])

subarray = a[:,1] # 3,1,1,5

indices = np.argsort(subarray) # Returns array([1,2,0,3])

result = a[indices]

:

a[np.argsort(a[:,1])]
+2

If you want to sort only one column (for example, the second column), you can do something like:

from operator import itemgetter
a = [[0, 3], [5, 1], [2, 1], [4, 5]]
a_sorted = sorted(a, key=itemgetter(1))

If there is more than one key, use numpy.lexsort () as indicated in other answers.

+1
source

All Articles