NumPy lexsort() Function:
The NumPy lexsort() method uses a sequence of keys to perform an indirect stable sort.
lexsort() returns an array of integer indices that describes the sort order by multiple columns, when multiple sorting keys are provided, that are interpreted as columns. The primary sort order is determined by the last key in the sequence, the secondary sort order by the second-to-last key, and so on.
The keys argument should be a sequence of objects which are converted to arrays of the same shape.
If the keys parameter is a 2D array, the rows are regarded as sorting keys, and sorting is done according to the last row, second last row, and so on.
Syntax:
numpy.lexsort(keys, axis=-1)
Parameters
keys: This is required. It indicates the k different ‘columns’ which are to be sorted. The last column is the primary sort key. (or row if keys argument is a 2D array)
axis: This is optional. Indicate which axis should be sorted indirectly. Sort over the last axis by default.
Return Value:
An array of indices in which the keys are sorted along the given axis is returned.
- Sorting 2D Numpy Array by column or row in Python | How to sort the NumPy array by column or row in Python?
- Count occurrences of a value in NumPy array in Python | numpy.count() in Python
- Python Programming – NumPy
NumPy lexsort() Function in Python
Example
Approach:
- Import numpy module using the import keyword
- Pass some random list(first column)as an argument to the array() function to
create an array. - Store it in a variable.
- Pass some random list(second column) as an argument to the array() function to
create another array - Store it in another variable.
- Pass the given second and first columns(b, a) as the arguments to the lexsort() function
of the numpy module which sorts the a column first and b column second. - Print the above obtained array indices
- Printing the values of first and second columns(a, b).
- The Exit of the Program.
Below is the implementation:
# Import numpy module using the import keyword import numpy as np # Pass some random list(first column)as an argument to the array() function to # create an array. # Store it in a variable. a = np.array([1, 12, 1, 2, 10, 5, 6]) # Pass some random list(second column) as an argument to the array() function to # create another array # Store it in another variable. b = np.array([3, 9, 1, 10, 20, 5, 12]) # Pass the given second and first columns(b, a) as the arguments to the lexsort() function # of the numpy module which sorts the a column first and b column second. arry_indices = np.lexsort((b, a)) # Print the above obtained array indices print("The above obtained array indices:") print(arry_indices) # Printing the values of first and second columns(a, b) print("Printing sorted a and b column values:") for k in arry_indices: print(a[k], b[k])
Output:
The above obtained array indices: [2 0 3 5 6 4 1] Printing sorted a and b column values: 1 1 1 3 2 10 5 5 6 12 10 20 12 9