What is the numpy.lexsort() function in Python?

Overview

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.

Syntax

numpy.lexsort(keys, axis=- 1)

Parameters

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 axis 1, which is the second axis running horizontally across columns.

Return value

The lexsort() function returns array of indices that sort the keys along the specified axis.

Example

import numpy as np
# creating lists of numbers
mylist1 = [1, 2, 3, 4, 5]
mylist2 = [7, 8, 9, 10, 11]
# implementing the lexsort() function to sorth mylist1 first
myarray = np.lexsort((mylist2, mylist1))
print(myarray)

Explanation

  • Line 1: We import the numpy module.
  • Line 3–4: We create lists mylist1 and mylist2 representing the keys (the columns to be sorted.)
  • Line 7: We implement the lexsort() function on both keys, mylist1 and mylist2. The result is assigned to a variable myarray.
  • Line 9: We print the sorted array, myarray.

Free Resources