Sort, Search and Counting Functions

A.) Sorting functions
1.) sort(): It returns a sorted copy of the array. It takes parameters (array, axis, kind). Here for parameters axis means either along cloumns or rows or flattened array, kind parameter(optional) means type of sorting it will use like- quicksort, mergesort.
 
2.) argsort(): It returns the indices that would sort an array. It aslo has same parameters as sort().
Sorting
import numpy as np
1. sort()
## Sorting along flattened array
a = np.array([[5,4],[3,1]])
np.sort(a)
array([[4, 5],
       [1, 3]])
## Sorting along first axis i.e, columns(down)
np.sort(a,axis=0)
array([[3, 1],
       [5, 4]])
2. argsort()
np.argsort(a.flatten())
array([3, 2, 1, 0], dtype=int64)
## Sorting along first axis
np.argsort(a,axis=0)
array([[1, 1],
       [0, 0]], dtype=int64)
## Sorting along last axis
np.argsort(a,axis=1)
array([[1, 0],
       [1, 0]], dtype=int64)
B.)Searching functions
1.) agrmax(): It returns the indices of the maximum values along an axis. Similarly, agrmin() functions work to find the minimum.
2.) argwhere(): It finds the indices of array elements that are non-zero, grouped by element. Here this function takes a parameter as a condition and returns the indices of elements satisfying that condition. There are tons of searching and sorting functions like nonzero(), partition(), where(). So, for the core details of any function, you can go to the documentation of Numpy. The link is
 
C.)Counting function
1.) count_nonzero(): It returns the number of non-zero elements along the specified axis.

Searching

import numpy as np

1. argmax()

a = np.arange(6).reshape(2,3)
print(a)
## argsort() for flattened array
np.argmax(a)
[[0 1 2]
 [3 4 5]]
5
## agrsort() along first axis
np.argmax(a, axis=0)
array([1, 1, 1], dtype=int64)

2. argwhere()

## It is returning the indices of elements which are satisfying the condition.
np.argwhere(a>=2)
array([[0, 2],
       [1, 0],
       [1, 1],
       [1, 2]], dtype=int64)
Counting
count_nonzero()
np.count_nonzero(np.array([[0,1],[1,1],[2,0]]))
[[0 1]
 [1 1]
 [2 0]]
4
np.count_nonzero(np.array([[0,1],[1,1],[2,0]]), axis=0)
array([2, 2], dtype=int64)
np.count_nonzero(np.array([[0,1],[1,1],[2,0]]), axis=1)
array([1, 2, 1], dtype=int64)

Leave a Comment

Your email address will not be published. Required fields are marked *