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

To compute indexer and find the previous index value if no exact match, use the index.get_indexer() method with the method parameter set to ffill (forward fill).

Syntax

index.get_indexer(target, method='ffill')

Parameters

The key parameters are:

  • target − Array-like values to find indexers for
  • method − Set to 'ffill' to find the previous index value for non-exact matches

Example

Let's create a Pandas index and demonstrate how get_indexer() works with forward fill ?

import pandas as pd

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

# Display the Pandas index
print("Pandas Index...")
print(index)

# Return the number of elements in the index
print("\nNumber of elements in the index:")
print(index.size)

# Compute indexer and mask using the "get_indexer"
# Find the previous index value if no exact match using the "method" parameter.
# The value is set "ffill"
print("\nGet the indexes...")
print(index.get_indexer([30, 20, 75, 80, 50, 59], method="ffill"))
Pandas Index...
Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')

Number of elements in the index:
7

Get the indexes...
[2 1 6 6 4 4]

How It Works

The get_indexer() method with method='ffill' works as follows:

  • 30 − Exact match found at index 2
  • 20 − Exact match found at index 1
  • 75 − No exact match, uses previous value (70 at index 6)
  • 80 − No exact match, uses previous value (70 at index 6)
  • 50 − Exact match found at index 4
  • 59 − No exact match, uses previous value (50 at index 4)

Conclusion

Use get_indexer() with method='ffill' to find the position of the nearest previous value when no exact match exists. This is useful for time series data and sorted indices where you need the last valid position.

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

350 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements