Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to sort a Numpy Array | Python

How to sort a Numpy Array | Python

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 using Python. Let’s try to understand them with the help of different methods. In this article, we will see How to sort a Numpy Array in Python.

Sort a Numpy Array using the sort()

Here we sort the given array based on the axis using the sort() method i.e. create a sorted copy of the given numpy array. 

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]

Sort a Numpy Array using sort() function

Here we sort the given array using the sort() method i.e. we sort the given numpy array inplace. 

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 a Numpy Array using argsort()

Get the indices which can return sorted array using argsort() method.

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]

Sort a Numpy Array using a sequence of keys

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]

RELATED ARTICLES

Most Popular

Recent Comments