numpy.searchsorted() in Python
The numpy.searchsorted() function is used to find index positions where new values can be inserted into a sorted NumPy array while keeping the array order intact. It works using binary search, making it efficient for large arrays.
In this simple example, we check where the number 15 should be inserted into a sorted array [10, 20, 30].
import numpy as np
arr = np.array([10, 20, 30])
val = 15
idx = np.searchsorted(arr, val)
print("Insertion index:", idx)
Output
Insertion index: 1
Explanation: number 15 should be placed at index 1 (between 10 and 20) to keep the array sorted.
Syntax
numpy.searchsorted(arr, values, side='left', sorter=None)
Parameters:
- arr (array_like): Sorted input array.
- values (array_like): Value(s) to insert.
- side ('left' or 'right', optional) 'left': index of first suitable location and 'right': index of last suitable location.
- sorter (array_like, optional): Indices that sort arr (from argsort).
Returns: indices (ndarray): Insertion points, same shape as values.
Examples
Example 1: In this example, we insert a number into a sorted array and find its index.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
val = 30
idx = np.searchsorted(arr, val)
print ("Array:", arr)
print ("Value to insert:", val)
print ("Insertion index:", idx)
Output
Array: [10 20 30 40 50] Value to insert: 30 Insertion index: 2
Explanation: 30 fits at index 2 in the sorted array (before the existing 30).
Example 2: Here, we insert the same number but use side='right' to place it after existing equal values.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
val = 30
idx = np.searchsorted(arr, val, side='right')
print ("Array:", arr)
print ("Value to insert:", val)
print ("Insertion index:", idx)
Output
Array: [10 20 30 40 50] Value to insert: 30 Insertion index: 3
Explanation: With side='right', insertion happens after the existing 30, i.e., at index 3.
Example 3: In this example, we pass an array of values to np.searchsorted() and it returns the insertion indices for each value.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
vals = np.array([30, 60, 5])
idx = np.searchsorted(arr, vals)
print ("Array:", arr)
print ("Values to insert:", vals)
print ("Insertion indices:", idx)
Output
Array: [10 20 30 40 50] Values to insert: [30 60 5] Insertion indices: [2 5 0]
Explanation:
- 30 -> index 2 (before the existing 30).
- 60 -> index 5 (end of array).
- 5 -> index 0 (start of array).