Pandas Index.asof() in Python

In this tutorial, you will learn about the Index.asof() function in Python with Pandas.

Python is amongst the finest languages used for performing data analysis just because of the packages it provides. One such package is the Pandas. Here we will be learning about Index.asof() function of the Pandas library.

Index.asof() function returns the label from the index or the previous label if not present. An important point to note is the Index needs to be sorted otherwise the function will return an error.

Syntax: Index.asof(label)

Label: Object
      Label up to which the method returns the index label.

Return: Object
      If it is in the index then the passed label. If there is no such label then NaN and if the passed label is not in the index then the previous label.

Let’s understand this with an example.
Here we have a list of 6 random numbers in an unsorted format. First, we will create the indexes of the numbers.

import pandas as pd

num=[10,23,14,16,63,24]
#sorting the numbers.
num.sort()
#creating Index
indx=pd.Index(num)

print(indx)
Output: Int64Index([10, 14, 16, 23, 24, 63], dtype='int64')

Now let’s find the latest label in the index up to 26

print(indx.asof(26))
output: 24

If we had performed the same task without sorting the list, we would have got an error.

import pandas as pd

num=[10,23,14,16,63,24]

#creating Index
indx=pd.Index(num)

print(indx.asof(26))
Output: index must be monotonic increasing or decreasing

Now let’s find the latest label in the index up for 8

print(indx.asof(8))
Output: nan

We can see the 8 is not in the list in fact it is the smallest of all the numbers available therefore we get a nan in return.
Let’s see the other case where we find the label in the index for 70, which is also not in the list.

print(indx.asof(70))
Output: 63

Also, read: Put legend outside the Matplotlib plot with Pandas in Python

Why didn’t we get nan as output? The reason is asof() returns the previous label if the passed label not on the list. When the passed label was 8 there was no previous label available hence the output was nan.

Leave a Reply

Your email address will not be published. Required fields are marked *