NumPy | searchsorted method
searchsorted(~) method returns the index of elements if they were to be added in to the sorted array.
The input array. If
sorter is not provided, then
a must be sorted in ascending order.
The values whose index you seek if they were to be added into a sorted input array.
The two possible values are as follows:
Returns the first suitable index if value is duplicate
Returns the last suitable index if value is duplicate
If the input array a is not sorted in ascending order, then we must provide a 1D array that holds the indices that make a in sorted ascending order.
A Numpy array containing the index of elements if they were to be added in to the sorted array.
Search sorted with side=left
Find the index of the value 2 if it were added into the array
np.searchsorted([1,2,3,4], 2) # or with parameter side=left1
Here, 1 is returned because when the value 2 is inserted into the array, it would be placed in the 1st index (i.e. the left of its duplicate).
Also, it is important that our input array is sorted in ascending order since we did not provide the sorter argument.
Search sorted with side=right
To get the right index of the value:
np.searchsorted([1,2,3,4], 2, side="right")2
Here, 2 is returned because when the value 2 is inserted into the array, it would be placed in the 2nd index (i.e. the right of its duplicate).
Passing in an array of values
Instead of passing in just a scalar, we can also pass in an array of values like follows:
np.searchsorted([2,3,4,5], [0,3,6])array([0, 1, 4])
Notice how each element is considered one by one - this is why the index of value 6 is 4.
Passing in a sorter
searchsorted(~) requires that your input array is sorted in ascending order. If it is not, we need to pass in a 1D array that sorts our input array in ascending order, like so:
np.searchsorted([2,1,3,4], 2, sorter=[1,0,2,3])1