Numpy | Sorting, Searching and Counting

Sorting

Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are in numerical or lexicographical order. In Numpy, we can perform various sorting operations using the various functions that are provided in the library like sort, lexsort, argsort etc.

numpy.sort() : This function returns a sorted copy of an array.


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

 
numpy.argsort() : This function returns the indices that would sort an array.

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

 
numpy.lexsort() : This function returns an indirect stable sort using a sequence of keys.

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

 

Function Description
numpy.ndarray.sort() Sort an array, in-place.
numpy.msort() Return a copy of an array sorted along the first axis.
numpy.sort_complex() Sort a complex array using the real part first, then the imaginary part.
numpy.partition() Return a partitioned copy of an array.
numpy.argpartition() Perform an indirect partition along the given axis using the algorithm specified by the kind keyword.

Searching

Searching is an operation or a technique that helps finds the place of a given element or value in the list. Any search is said to be successful or unsuccessful depending upon whether the element that is being searched is found or not. In Numpy, we can perform various searching operations using the various functions that are provided in the library like argmax, argmin, nanaargmax etc.

numpy.argmax() : This function returns indices of the max element of the array in a particular axis.


# Python Program illustrating
# working of argmax()

import numpy as geek 

# Working on 2D array
array = geek.arange(12).reshape(3, 4)
print("INPUT ARRAY : \n", array)

# No axis mentioned, so works on entire array
print("\nMax element : ", geek.argmax(array))

# returning Indices of the max element
# as per the indices
print(("\nIndices of Max element : "
      , geek.argmax(array, axis=0)))
print(("\nIndices of Max element : "
      , geek.argmax(array, axis=1)))

Output :

INPUT ARRAY : 
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Max element :  11

Indices of Max element :  [2 2 2 2]

Indices of Max element :  [3 3 3]

 
numpy.nanargmax() : This function returns indices of the max element of the array in a particular axis ignoring NaNs.The results cannot be trusted if a slice contains only NaNs and Infs.


# Python Program illustrating
# working of nanargmax()

import numpy as geek 

# Working on 1D array
array = [geek.nan, 4, 2, 3, 1]
print("INPUT ARRAY 1 : \n", array)

array2 = geek.array([[geek.nan, 4], [1, 3]])

# returning Indices of the max element
# as per the indices ingnoring NaN
print(("\nIndices of max in array1 : "
       , geek.nanargmax(array)))

# Working on 2D array
print("\nINPUT ARRAY 2 : \n", array2)
print(("\nIndices of max in array2 : "
      , geek.nanargmax(array2)))

print(("\nIndices at axis 1 of array2 : "
      , geek.nanargmax(array2, axis = 1)))

Output :

INPUT ARRAY 1 : 
 [nan, 4, 2, 3, 1]

Indices of max in array1 :  1

INPUT ARRAY 2 : 
 [[ nan   4.]
 [  1.   3.]]

Indices of max in array2 :  1

Indices at axis 1 of array2 :  [1 1]

 
numpy.argmin() : This function returns the indices of the minimum values along an axis.


# Python Program illustrating
# working of argmin()

import numpy as geek 

# Working on 1D array
array = geek.arange(8)
print("INPUT ARRAY : \n", array)


# returning Indices of the min element
# as per the indices
print("\nIndices of min element : ", geek.argmin(array, axis=0))

Output :

INPUT ARRAY : 
 [0 1 2 3 4 5 6 7]

Indices of min element :  0

 

Function Description
numpy.nanargmin() Return the indices of the minimum values in the specified axis ignoring NaNs.
numpy.argwhere() Find the indices of array elements that are non-zero, grouped by element.
numpy.nonzero() Return the indices of the elements that are non-zero.
numpy.flatnonzero() Return indices that are non-zero in the flattened version of a.
numpy.where() Return elements chosen from x or y depending on condition.
numpy.searchsorted() Find indices where elements should be inserted to maintain order.
numpy.extract() Return the elements of an array that satisfy some condition.

Counting

numpy.count_nonzero() : Counts the number of non-zero values in the array .


# Python Program illustrating
# working of count_nonzero()

import numpy as np
 
# Counting a number of 
# non-zero values
a = np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])
b = np.count_nonzero(([[0,1,7,0,0],[3,0,0,2,19]]
                     , axis=0))

print("Number of nonzero values is :",a)
print("Number of nonzero values is :",b)

Output :

Number of nonzero values is : 5
Number of nonzero values is : [1, 1, 1, 1, 1]

 



  • Last Updated : 25 Jan, 2024

Share your thoughts in the comments
Similar Reads