Locate ordered insertion points
Determine where incoming measurements, timestamps, or scores belong in an already sorted sequence without inserting or copying the sequence.
NumPy · Function
Find insertion positions in a sorted array so added values preserve its order. Choose left or right placement for duplicates, and optionally provide sort indices for an array that is not physically sorted.
NumPy.searchsorted finds positions for inserting one or more values into a sorted one-dimensional array. It returns the first valid position by default, or the position after equal values when side="right"; an optional sorter lets the input array remain unsorted.
numpy.searchsorted(a, v, side='left', sorter=None)| Name | Type | Description |
|---|---|---|
a | array_like | Sorted one-dimensional input array, unless sorter supplies its ascending sort order. |
v | array_like | Values whose insertion positions are requested. |
side | {'left', 'right'}, optional | Either 'left' or 'right'; selects placement before or after equal values. |
sorter | 1-D array_like, optional | One-dimensional integer indices that sort a into ascending order. |
indices: int or array of ints. Insertion points; an integer is returned when v is scalar, otherwise an array with v's shape.
import numpy as np
a = np.array([10, 20, 30, 40])
values = np.array([5, 20, 35, 50])
left = np.searchsorted(a, values)
right = np.searchsorted(a, values, side="right")
print(left) # [0 1 3 4]
print(right) # [0 2 3 4]The two side choices show whether equal values are inserted before or after existing matches.
Determine where incoming measurements, timestamps, or scores belong in an already sorted sequence without inserting or copying the sequence.
Use side='left' or side='right' to define whether duplicate keys resolve to the first or last matching boundary.
Compute positions against an original array while retaining its layout by passing np.argsort(a) as sorter.
It returns insertion points that preserve the ordering of a. With the default side="left", an equal value is placed before existing equal values; side="right" places it after them.
Follow-up: How can you use an unsorted array? Supply sorter=np.argsort(a), which provides integer indices that sort a into ascending order.
v may be scalar or array-like. The result is an integer for a scalar v and an array with the same shape as v for array-like input.
Follow-up: What boundary results should you expect? A value below all elements returns 0, and one above all elements returns the length of a.
a must be sorted in ascending order when sorter is None. If a is not sorted, pass a one-dimensional integer index array in sorter that sorts a ascendingly.
Follow-up: Why is sorter useful? It lets the data remain in its original order while searchsorted interprets it through the sorted index order.
numpy.argsortnumpy.sortnumpy.searchsorted