Time for action – using searchsorted
The searchsorted()
function gets the index of a value in a sorted array. An example should make this clear:
To demonstrate, create an array with
arange()
, which of course is sorted:a = np.arange(5)
Time to call the
searchsorted()
function:indices = np.searchsorted(a, [-2, 7]) print("Indices", indices)
The indices, which should maintain the sort order:
Indices [0 5]
Construct the full array with the
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]
What just happened?
The searchsorted()
function gave us indices 5
and 0
for 7
and -2
. With these indices, we made the array [-2, 0, 1, 2, 3, 4, 7]
, so the array remains sorted (see sortedsearch.py
):
from __future__ import print_function
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]))