NumPy ndarray.searchsorted()
The numpy.ndarray.searchsorted()
method finds the indices where elements should be inserted to maintain order. It works on sorted arrays and allows inserting elements from the left or right side of existing values.
Syntax
</>
Copy
ndarray.searchsorted(v, side='left', sorter=None)
Parameters
Parameter | Type | Description |
---|---|---|
v | 1-D array_like | Values to insert into the sorted array. |
side | {‘left’, ‘right’}, optional | Specifies whether to insert at the leftmost or rightmost suitable index. Default is 'left' . |
sorter | 1-D array_like, optional | An array of indices that sort ndarray . Useful for searching in an indirectly sorted array. |
Return Value
Returns an integer or an array of integers indicating the indices where elements should be inserted while preserving order.
Examples
1. Basic Usage of ndarray.searchsorted()
Find the index where a value should be inserted in a sorted array.
</>
Copy
import numpy as np
# Sorted input array
arr = np.array([1, 3, 5, 7])
# Value to insert
value = 4
# Finding the insertion index
index = arr.searchsorted(value)
# Printing the result
print(index) # Output: 2 (4 should be inserted at index 2 to maintain order)
Output:
2
2. Using the side
Parameter
Specifying whether to insert on the leftmost or rightmost occurrence of the existing values.
</>
Copy
import numpy as np
# Sorted input array with duplicate values
arr = np.array([1, 2, 2, 3, 5])
# Value to insert
value = 2
# Inserting on the left
left_index = arr.searchsorted(value, side='left')
# Inserting on the right
right_index = arr.searchsorted(value, side='right')
# Printing results
print(left_index) # Output: 1 (Inserts before the first occurrence of 2)
print(right_index) # Output: 3 (Inserts after the last occurrence of 2)
Output:
1
3
3. Searching for Multiple Values
Using an array of values to find multiple insertion indices.
</>
Copy
import numpy as np
# Sorted input array
arr = np.array([10, 20, 30, 40])
# Values to insert
values = np.array([25, 35, 5])
# Finding the insertion indices
indices = arr.searchsorted(values)
# Printing results
print(indices) # Output: [2 3 0] (Each value's correct insertion index)
Output:
[2 3 0]
4. Using the sorter
Parameter
Searching within an indirectly sorted array by providing a sorter array.
</>
Copy
import numpy as np
# Unsorted input array
arr = np.array([30, 10, 20, 40])
# Indices that sort the array
sorter = np.argsort(arr)
# Values to insert
values = np.array([25, 35])
# Finding the insertion indices using sorter
indices = arr.searchsorted(values, sorter=sorter)
# Printing results
print(indices) # Output: [2 3] (Based on sorted order of arr: [10, 20, 30, 40])
Output:
[2 3]