dcalmeida
dcalmeida

Reputation: 403

Sorting NumPy array with two columns

I have the following array, which contains X and Y coordinates:

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

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.]])

Upvotes: 0

Views: 1046

Answers (1)

omri_saadon
omri_saadon

Reputation: 10621

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

Upvotes: 3

Related Questions