How to use Sequence of Keys In NumPy

Sorting a array using a sequence of keys allows us to sort an array based on multiple criteria.

You can use this method with np.lexsort() function. The lexsort() function returns an array of indices that would sort the original array.

Example

Get stable sort using a sequence of keys.

Python3




import numpy as np
  
# Numpy array created
# First column
a = np.array([9, 3, 1, 3, 4, 3, 6])
  
# Second column
b = np.array([4, 6, 9, 2, 1, 8, 7])
print('column a, column b')
for (i, j) in zip(a, b):
    print(i, ' ', j)
  
# Sort by a then by b
ind = np.lexsort((b, a))
print('Sorted indices->', ind)


Output: 

column a, column b
9 4
3 6
1 9
3 2
4 1
3 8
6 7
Sorted indices-> [2 3 1 5 4 6 0]

NumPy Array Sorting | How to sort NumPy Array

Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean.

In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy:

  • Using np.sort() function
    • in-line sort
    • sorting along different axes
  • Using np.argsort() function
  • Using np.lexsort() function

Similar Reads

Using sort() function

sort() method sorts the element of a given data structure (here array). Call the sort function with the array object to sort the elements....

Using argsort()

...

Using Sequence of Keys

...

Conclusion

argsort() method is an indirect way of sorting the NumPy array along a given axis....