The searchsorted
function allows us to get the index of a value in a sorted array, where it could be inserted so that the array remains sorted. An example should make this clear. Perform the following steps:
arange
, which of course is sorted.a = np.arange(5)
searchsorted
function.indices = np.searchsorted(a, [-2, 7]) print "Indices", indices
The following are the indices which should maintain the sort order:
Indices [0 5]
insert
function.print "The full array", np.insert(a, indices, [-2, 7])
This gives us the full array:
The full array [-2 0 1 2 3 4 7]
The searchsorted
function gave us indices 5 and 0 for 7 and -2. With these indices, we would make the array [-2, 0, 1, 2, 3, 4, 7]
—so the array remains sorted (see sortedsearch.py
).
import numpy as np a = np.arange(5) indices = np.searchsorted(a, [-2, 7]) print "Indices", indices print "The full array", np.insert(a, indices, [-2, 7])