How to Sort a Numpy Array | python

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

# import libraries

import numpy as np

  
# sort by first axis

a = np.array ([[ 12 , 15 ], [ 10 , 1 ]])

arr1 = np.sort (a, axis = 0

 

print ( "Along first axis:" , arr1) 

 

 
# sort by last axis

a = np.array ([[ 10 , 15 ], [ 12 , 1 ]])

arr2 = np.sort (a, axis = - 1

print ( "Along first axis:" , arr2)

 

 

a = np.array ([[ 12 , 15 ], [ 10 , 1 ]])

arr1 = np.sort (a, axis = None

print ( "Along none axis: " , arr1)

Exit:

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

Example # 2: Get the indexes that a sorted array can return using the argsort () method

# Python code for demo
# working of numpy.argsort

import numpy as np

 
# Numpy array created

a = np.array ([ 9 , 3 , 1 , 7 , 4 , 3 , < code class = "value"> 6 ])

 
# unsorted print array

print ( `Original array:` , a)

  
# Sort array indices

b = np.argsort (a)

print ( `Sorted indices of original array- & gt;` , b)

 
# Get a sorted array using sorted indices
# c is a temporary array created from the same len as b

c = np.zeros ( len ( b), dtype = int )

for i in range ( 0 , len (b)):

  c [i] = a [b [i]]

print ( `Sorted array- & gt;` , c)

Output:

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

Example # 3: Get a 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 then by b

ind = np.lexsort ((b, a)) 

print ( `Sorted indices- & gt;` , ind)

Exit :

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