NumPy | searchsorted method
Start your free 7-days trial now!
NumPy's searchsorted(~)
method returns the index of elements if they were to be added into the sorted array.
Parameters
1. a
| array_like
The input array. If sorter
is not provided, then a
must be sorted in ascending order.
2. v
| array_like
The values whose index you seek if they were to be added into a sorted input array.
3. side
link | string
| optional
The two possible values are as follows:
Parameter value | Meaning |
---|---|
| Returns the first suitable index if value is duplicate |
| Returns the last suitable index if value is duplicate |
By default, side="left"
.
4. sorter
link | array-like
| optional
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.
Return value
A NumPy array containing the index of elements if they were to be added in to the sorted array.
Examples
Search sorted with side=left
To find the index of the value 7
if it were added into the array [6,7,8,9]
:
np.searchsorted([6,7,8,9], 7) # or with parameter side=left
1
Here, 1
is returned because when the value 7
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([6,7,8,9], 7, side="right")
2
Here, 2
is returned because when the value 7
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
The method 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