Python - Find indices where elements should be inserted to maintain order in Pandas Index

To find indices where elements should be inserted to maintain sorted order in a Pandas Index, use the searchsorted() method. This method returns the insertion positions that would keep the index sorted.

Syntax

The basic syntax for the searchsorted() method is ?

index.searchsorted(value, side='left')

Parameters

  • value − The value(s) to insert
  • side − 'left' (default) or 'right' for insertion position

Finding Insertion Position for Single Value

Here's how to find where a single element should be inserted ?

import pandas as pd

# Creating Pandas index
index = pd.Index([10, 20, 30, 40, 50])
print("Pandas Index:")
print(index)

# Find insertion position for value 45
position = index.searchsorted(45)
print(f"\nInsertion position for 45: {position}")
Pandas Index:
Index([10, 20, 30, 40, 50], dtype='int64')

Insertion position for 45: 4

Finding Insertion Positions for Multiple Values

You can also find insertion positions for multiple values at once ?

import pandas as pd

index = pd.Index([10, 20, 30, 40, 50])
print("Original Index:")
print(index)

# Find positions for multiple values
values_to_insert = [5, 25, 35, 60]
positions = index.searchsorted(values_to_insert)

print(f"\nValues to insert: {values_to_insert}")
print(f"Insertion positions: {positions}")
Original Index:
Index([10, 20, 30, 40, 50], dtype='int64')

Values to insert: [5, 25, 35, 60]
Insertion positions: [0 2 3 5]

Using Left vs Right Side

The 'side' parameter determines insertion behavior for duplicate values ?

import pandas as pd

index = pd.Index([10, 20, 30, 30, 40, 50])
print("Index with duplicates:")
print(index)

value = 30
left_pos = index.searchsorted(value, side='left')
right_pos = index.searchsorted(value, side='right')

print(f"\nInsertion position for {value} (left side): {left_pos}")
print(f"Insertion position for {value} (right side): {right_pos}")
Index with duplicates:
Index([10, 20, 30, 30, 40, 50], dtype='int64')

Insertion position for 30 (left side): 2
Insertion position for 30 (right side): 4

Comparison

Side Parameter Behavior with Duplicates Use Case
'left' (default) Insert before existing duplicates Maintain stable sort
'right' Insert after existing duplicates Group duplicates together

Conclusion

The searchsorted() method efficiently finds insertion positions to maintain sorted order in Pandas Index. Use 'left' or 'right' side parameter to control behavior with duplicate values.

Updated on: 2026-03-26T16:22:56+05:30

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements