Open In App

NumPy Array Sorting | How to sort NumPy Array

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

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.

There are two cases of sorting array with the sort() method:

  • Sort NumPy array in place
  • Sort NumPy array along axes

We’ll cover both these methods with an example below:

Sort array In-Place

Sorting an array in place means directly sorting original array elements.

It does not create a new array copy and is very memory efficient.

Example

Using the sort() method to sort elements in the NumPy array in place.

Python3




# importing libraries
import numpy as np
  
a = np.array([12, 15, 10, 1])
print("Array before sorting",a)
a.sort()
print("Array after sorting",a)


Output:

Array before sorting [12 15 10 1] 
Array after sorting [ 1 10 12 15]

Sort Array Along Different Axes

This method creates a sorted copy of the given NumPy array. 

It is mostly used in a multi-dimensional array when you want to sort along a given dimension.

Example

Using the sort() method to elements in the NumPy array along the axis

Python3




# importing libraries
import numpy as np
# sort along the first axis
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = 0)        
print ("Along first axis : \n", arr1)        
# sort along the last axis
a = np.array([[10, 15], [12, 1]])
arr2 = np.sort(a, axis = -1)        
print ("\nAlong first axis : \n", arr2)
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = None)        
print ("\nAlong none axis : \n", arr1)


Output: 

Along first axis :  [[10  1] [12 15]]Along first axis :  [[10 15] [ 1 12]]Along none axis :  [ 1 10 12 15]

Using argsort()

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

It returns an array of indices that would sort the original array in ascending order.

Example

Using argsort() to sort elements in the NumPy array

Python3




import numpy as np
  
# Numpy array created
a = np.array([9, 3, 1, 7, 4, 3, 6])
  
# unsorted array print
print('Original array:\n', a)
  
# Sort array indices
b = np.argsort(a)
print('Sorted indices of original array->', b)
  
# To get sorted array using sorted indices
# c is temp array created of same len as of b
c = np.zeros(len(b), dtype = int)
for i in range(0, len(b)):
    c[i]= a[b[i]]
print('Sorted array->', c)


Output: 

Original array:
[9 3 1 7 4 3 6]
Sorted indices of original array-> [2 1 5 4 6 3 0]
Sorted array-> [1 3 3 4 6 7 9]

Using Sequence of Keys

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]

Also Check: Sorting, Searching and Counting in NumPy

Conclusion

Sorting the NumPy array makes finding duplicate, maximum, and minimum elements easier. It is an essential operation of data manipulation, making it easier to work with data.

In this tutorial, we have covered three methods on how to sort a array in NumPy i.e., sort(), argsort() and lexsort(). All these methods provide different functionalities to sort ndarray in NumPy. We have explained the methods in easy words with examples to give you a complete understanding of the topic.



Last Updated : 01 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads