NumPy - lexsort() function
The NumPy lexsort() function performs an indirect stable sort using a sequence of keys.
When multiple sorting keys are provided, it can be interpreted as columns, 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, its rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc.
Syntax
numpy.lexsort(keys, axis=-1)
Parameters
keys |
Required. Specify The k different 'columns' to be sorted. The last column (or row if keys is a 2D array) is the primary sort key. |
axis |
Optional. Specify the axis to be indirectly sorted. By default, sort over the last axis. |
Return Value
Returns an array of indices that sort the keys along the specified axis.
Example:
In the example below, lexsort() function is used to sort by x column first then by y column.
import numpy as np #x column - First column x = np.array([10, 20, 10, 20, 10, 25, 10]) #y column - Second column y = np.array([40, 10, 45, 60, 50, 25, 30]) #getting the array of indices that sorts #x column first, y column second indices = np.lexsort((y, x)) #displaying the indices print("Array of indices to sort columns") print(indices) #using indices to sort columns print("\nSorted x and y columns:") for i in indices: print(x[i], y[i])
The output of the above code will be:
Array of indices to sort columns [6 0 2 4 1 3 5] Sorted x and y columns: 10 30 10 40 10 45 10 50 20 10 20 60 25 25
❮ NumPy - Functions