The lexsort()
function in Python is used to perform an indirect stable sort using a sequence of keys.
Given multiple sorting keys, which is interpreted as columns in a spreadsheet, the lexsort()
function returns an array of integer indices which describes the sort order by multiple columns. The last key given in the sequence is used for the primary sort order, while the second-to-last key is used for the secondary sort order, and so on.
Note: Sort order here means the order in which the elements of a given array is sorted.
numpy.lexsort(keys, axis=- 1)
The lexsort()
function takes the following parameter values:
keys
: This represents the columns of the array or tuple containing K(N)-shaped sequences to be sorted. The last column is the primary sort key if the keys
argument is a 2D array.
axis
: This represents the axis (the row or column of the array) to be indirectly sorted. By default, the last axis is sorted. This is optional.
Note: Axes in numpy are defined for arrays having more than one dimension. A 2D array has two corresponding axes: axis
0
, which is the first axis running vertically downwards across rows and axis1
, which is the second axis running horizontally across columns.
The lexsort()
function returns array of indices that sort the keys along the specified axis.
import numpy as np# creating lists of numbersmylist1 = [1, 2, 3, 4, 5]mylist2 = [7, 8, 9, 10, 11]# implementing the lexsort() function to sorth mylist1 firstmyarray = np.lexsort((mylist2, mylist1))print(myarray)
numpy
module.mylist1
and mylist2
representing the keys
(the columns to be sorted.)lexsort()
function on both keys, mylist1
and mylist2
. The result is assigned to a variable myarray
.myarray
.