Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy lexicographic ordering

Tags:

python

numpy

I'd like to lexicographically sort the following array a (get index positions), but, I'm having problems understanding the numpy results:

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

For instance, I don't understand why [1, 2, 1] (a[:,0]) is sort-index 0 while [1, 1, 2] (a[:,1]) is index 5, even thought it should be samller than [1, 2, 1].

like image 626
orange Avatar asked Jul 02 '26 10:07

orange


1 Answers

The order of significance for keys is opposite to what you expected. In order to get expected result just flip the matrix upside down

>>> np.lexsort(np.flipud(a))
array([1, 4, 0, 2, 5, 3])
like image 98
matusko Avatar answered Jul 05 '26 00:07

matusko