dalmeida13 dalmeida13 - 4 years ago 229
Python Question

Sorting numpy array with two columns

I have the following array:

arr = array([[ 1., 3.],
[ 6., 6.],
[ 3., 0.],
[ 2., 5.],
[ 0., 3.],
[ 3., 3.],
[ 0., 6.]])


wich contains X and Y coordinates.
I would like to know how can I sort this array by first sorting X and after by sorting Y. I would like something like this:

new_ arr = array([[ 0., 3.],
[ 0., 6.],
[ 1., 3.],
[ 2., 5.],
[ 3., 0.],
[ 3., 3.],
[ 6., 6.]])

Answer Source

You can use the np lexort function, you can read more in here

numpy.lexsort(keys, axis=-1) Perform an indirect sort using a sequence of keys.

Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, it’s rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc

import numpy as np
arr = np.array([[ 1.,  3.],
             [ 6.,  6.],
             [ 3.,  0.],
             [ 2.,  5.],
             [ 0.,  3.],
             [ 3.,  3.],
             [ 0.,  6.]])
ind = np.lexsort(np.transpose(arr)[::-1])

print (arr[ind])

>>>[[ 0.  3.]
 [ 0.  6.]
 [ 1.  3.]
 [ 2.  5.]
 [ 3.  0.]
 [ 3.  3.]
 [ 6.  6.]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download