Time for action – using searchsorted

The searchsorted() function gets the index of a value in a sorted array. An example should make this clear:

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

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.