Time for action – using searchsorted

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:

  1. To demonstrate we will need an array that is sorted. Create an array with arange, which of course is sorted.
    a = np.arange(5)
  2. 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]
    
  3. 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]
    

What just happened?

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])
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset