Python Pandas - Return the label from the index or if not present, the previous one

To return the label from the index or if not present, the previous one, use the index.asof() method in Pandas. The asof() method returns the label (or index value) corresponding to a particular positional indexer, or the previous one if the exact label is not found.

Syntax

Index.asof(label)

Parameters:

  • label − The label to look for in the index

Basic Example

Let's create a pandas index and use asof() to find labels ?

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 label from the index or if not present, the previous one
print("\nLooking for exact match (30):")
print(index.asof(30))

print("\nLooking for non-existent label (43):")
print(index.asof(43))
Pandas Index...
Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')

Looking for exact match (30):
30

Looking for non-existent label (43):
40

How It Works

The asof() method works by:

  • First checking if the exact label exists in the index
  • If found, it returns that exact label
  • If not found, it returns the largest label that is still less than or equal to the search value
  • If no such label exists, it returns NaN

Edge Cases

Let's see what happens with edge cases ?

import pandas as pd

index = pd.Index([10, 20, 30, 40, 50])

# Label smaller than all index values
print("Searching for 5 (smaller than all):")
print(index.asof(5))

# Label larger than all index values
print("\nSearching for 100 (larger than all):")
print(index.asof(100))

# Label exactly matching
print("\nSearching for 20 (exact match):")
print(index.asof(20))
Searching for 5 (smaller than all):
nan

Searching for 100 (larger than all):
50.0

Searching for 20 (exact match):
20.0

With DateTime Index

The asof() method is particularly useful with datetime indexes for time-series data ?

import pandas as pd

# Creating a datetime index
dates = pd.date_range('2023-01-01', periods=5, freq='D')
index = pd.Index(dates)

print("DateTime Index:")
print(index)

# Looking for a date that doesn't exist
search_date = pd.Timestamp('2023-01-03 12:00:00')
print(f"\nSearching for {search_date}:")
print(index.asof(search_date))
DateTime Index:
DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04',
               '2023-01-05'],
              dtype='datetime64[ns]', freq='D')

Searching for 2023-01-03 12:00:00:
2023-01-03 00:00:00

Conclusion

The asof() method is useful for finding the nearest preceding value in a sorted index. It returns the exact match if found, otherwise the largest value less than or equal to the search term, making it ideal for time-series lookups.

---
Updated on: 2026-03-26T16:30:45+05:30

325 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements