By default, the leftmost index is returned, but you can specify side='right'
to return the rightmost index instead.
Determine the indices where the value 7 should be inserted, starting from the right:
import numpy as np arr = np.array([6, 7, 8, 9]) x = np.searchsorted(arr, 7, side=‘right’) print(x) |
Example explained: The number 7 should be inserted at index 2 to maintain the sort order.
The method searches from the right and returns the first index where 7 is not less than the next value.
To search for multiple values, use an array containing the specified values.
Determine the indices where the values 2, 4, and 6 should be inserted:
import numpy as np arr = np.array([1, 3, 5, 7]) x = np.searchsorted(arr, [2, 4, 6]) print(x) |