numpy.searchsorted#

numpy.searchsorted(a,v,side='left',sorter=None)[source]#

Find indices where elements should be inserted to maintain order.

Find the indices into a sorted arraya such that, if thecorresponding elements inv were inserted before the indices, theorder ofa would be preserved.

Assuming thata is sorted:

side

returned indexi satisfies

left

a[i-1]<v<=a[i]

right

a[i-1]<=v<a[i]

Parameters:
a1-D array_like

Input array. Ifsorter is None, then it must be sorted inascending order, otherwisesorter must be an array of indicesthat sort it.

varray_like

Values to insert intoa.

side{‘left’, ‘right’}, optional

If ‘left’, the index of the first suitable location found is given.If ‘right’, return the last such index. If there is no suitableindex, return either 0 or N (where N is the length ofa).

sorter1-D array_like, optional

Optional array of integer indices that sort array a into ascendingorder. They are typically the result of argsort.

Returns:
indicesint or array of ints

Array of insertion points with the same shape asv,or an integer ifv is a scalar.

See also

sort

Return a sorted copy of an array.

histogram

Produce histogram from 1-D data.

Notes

Binary search is used to find the required insertion points.

As of NumPy 1.4.0searchsorted works with real/complex arrays containingnan values. The enhanced sort order is documented insort.

This function uses the same algorithm as the builtin pythonbisect.bisect_left (side='left') andbisect.bisect_right(side='right') functions, which is also vectorizedin thev argument.

Examples

>>>importnumpyasnp>>>np.searchsorted([11,12,13,14,15],13)2>>>np.searchsorted([11,12,13,14,15],13,side='right')3>>>np.searchsorted([11,12,13,14,15],[-10,20,12,13])array([0, 5, 1, 2])

Whensorter is used, the returned indices refer to the sortedarray ofa and nota itself:

>>>a=np.array([40,10,20,30])>>>sorter=np.argsort(a)>>>sorterarray([1, 2, 3, 0])  # Indices that would sort the array 'a'>>>result=np.searchsorted(a,25,sorter=sorter)>>>result2>>>a[sorter[result]]30  # The element at index 2 of the sorted array is 30.
On this page