-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

NumPy Beginner's Guide
By :

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:
To demonstrate we will need an array that is sorted. Create an array with arange
, which of course is sorted.
a = np.arange(5)
It's time to call the 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]
Let's 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]
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,...
Change the font size
Change margin width
Change background colour