0
0
NumPydata~5 mins

np.searchsorted() for insertion points in NumPy

Choose your learning style9 modes available
Introduction

We use np.searchsorted() to find where to insert a value into a sorted list so the list stays sorted. It helps us quickly find the right spot without sorting again.

You want to add a new score into a sorted list of scores and keep it sorted.
You need to find the position to insert a timestamp into a sorted list of timestamps.
You want to quickly find where a new value fits in a sorted dataset for analysis.
You are merging sorted data and want to know insertion points without re-sorting.
Syntax
NumPy
np.searchsorted(sorted_array, values, side='left', sorter=None)

sorted_array must be sorted for correct results.

side='left' finds insertion point before existing entries; side='right' after.

Examples
Finds where to insert 4 in [1,3,5,7]. Result is 2 because 4 fits between 3 and 5.
NumPy
import numpy as np
arr = np.array([1, 3, 5, 7])
pos = np.searchsorted(arr, 4)
print(pos)
Finds insertion point after existing 5. Result is 3.
NumPy
pos_right = np.searchsorted(arr, 5, side='right')
print(pos_right)
Finds insertion points for multiple values at once.
NumPy
values = [0, 2, 6, 8]
positions = np.searchsorted(arr, values)
print(positions)
Sample Program

This program finds where to insert new ages into a sorted list of ages to keep it sorted.

NumPy
import numpy as np

# Sorted array of ages
ages = np.array([18, 22, 25, 30, 35])

# New ages to insert
new_ages = np.array([20, 25, 40])

# Find insertion points
positions = np.searchsorted(ages, new_ages)

print('Ages:', ages)
print('New ages:', new_ages)
print('Insertion positions:', positions)
OutputSuccess
Important Notes

If the array is not sorted, results will be incorrect.

Use side='right' to insert after existing equal values.

You can insert multiple values at once by passing an array of values.

Summary

np.searchsorted() finds where to insert values in a sorted array.

It helps keep data sorted without re-sorting after insertion.

Use side to control insertion before or after equal values.