Python Pandas - Compute indexer and find the next index value if no exact match

The get_indexer() method in Pandas allows you to find the positions of target values in an index. When no exact match exists, the method="bfill" parameter finds the next available index value (backward fill).

Creating a Pandas Index

First, let's create a Pandas index with some values ?

import pandas as pd

# Creating Pandas index
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
print("Pandas Index...")
print(index)
Pandas Index...
Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')

Using get_indexer() with bfill Method

The get_indexer() method returns the positions of target values. With method="bfill", it finds the next higher value's position when no exact match exists ?

import pandas as pd

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

# Find positions using bfill method
target_values = [30, 25, 58, 50, 55]
positions = index.get_indexer(target_values, method="bfill")

print("\nTarget values:", target_values)
print("Positions found:", positions)
Pandas Index...
Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')

Target values: [30, 25, 58, 50, 55]
Positions found: [2 2 5 4 5]

Understanding the Results

Let's break down how each target value maps to its position ?

import pandas as pd

index = pd.Index([10, 20, 30, 40, 50, 60, 70])
target_values = [30, 25, 58, 50, 55]
positions = index.get_indexer(target_values, method="bfill")

print("Index values:", index.tolist())
print("Index positions:", list(range(len(index))))
print()

for target, pos in zip(target_values, positions):
    if pos == -1:
        print(f"Target {target}: No match found (position {pos})")
    else:
        print(f"Target {target}: Found at position {pos} (value {index[pos]})")
Index values: [10, 20, 30, 40, 50, 60, 70]
Index positions: [0, 1, 2, 3, 4, 5, 6]

Target 30: Found at position 2 (value 30)
Target 25: Found at position 2 (value 30)
Target 58: Found at position 5 (value 60)
Target 50: Found at position 4 (value 50)
Target 55: Found at position 5 (value 60)

Comparison with Other Methods

Method Behavior When No Match
None (default) Exact match only Returns -1
bfill Next higher value Finds next available
ffill Previous lower value Finds previous available

Conclusion

The get_indexer() method with method="bfill" is useful for finding the next available index position when exact matches don't exist. This is particularly helpful in time series data or when you need to locate the nearest higher value in sorted data.

Updated on: 2026-03-26T16:31:37+05:30

824 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements