NumPy: Search Sorted Method

In Numpy Package, there is a function numpy.searchsorted() which is mainly used to search the indices into the sorted array such that, suppose if the elements in the array are inserted before the indices, the order of that array is still preserved.

Syntax:

numpy.serachsorted( arr, num, side='left',sorter=None)

Parameters: 

  • arr: The given array. If the given sorter is None, then the array must be sorted in ascending order, otherwise, the sorter must be used in an array for sorting it.
  • num: Values which we will insert into the given array.
  • side: {‘left’, ‘right’}, It is optional.
    If the side is 'left', the index of the first suitable location found will be given. If the side is 'right', it will return the last such index. If there is no suitable index it will return 0 or N.(where N is the length of the input array)
  • sorter: It is also optional.
    It is the array of integer indices that sort the array into ascending order. It is the result of argsort.

Return:

It is indices. It is the array of insertion points with the same shape as that of num.

Examples:

import numpy as np
array_1=[2,3,4,5,6,7]
num=10
res_array=np.searchsorted(array_1,num)
print(res_array)

Output: 6

Mon, 10/04/2021 - 18:13

Authored by

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.