Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to sort a Numpy Array | Python

  • Last Updated : 11 May, 2020

In this article, we will learn how to sort a Numpy array. There are multiple ways in Numpy to sort an array, based on the requirement. Let’s try to understand them with the help of examples.

Example #1: Simply sort the given array based on axis using sort() method.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




# 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]

Example #2: Get the indices which can return sorted array using argsort() method




# Python code to demonstrate 
# working of  numpy.argsort
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]

Example #3: Get stable sort using a sequence of keys.




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]




My Personal Notes arrow_drop_up