Python | Pandas Index.asof()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.asof()
function returns return the label from the index, or, if not present, the previous one. Assuming that the index is sorted, return the passed index label if it is in the index, or return the previous index label if the passed one is not in the index.
Note: The function only works with sorted Index. If not sorted it returns error.
Syntax: Index.asof(label)
Parameters :
label : The label up to which the method returns the latest index labelReturns : The passed label if it is in the index. The previous label if the passed label is not in the sorted index or NaN if there is no such label.
Example #1: Use Index.asof()
function to return the latest index label upto the passed index label.
# importing pandas as pd import pandas as pd # Creating the Index df = pd.Index([ 17 , 69 , 33 , 15 , 19 , 74 , 10 , 5 ]) # Print the Index df |
Output :
Let’s sort the index labels first
# sorting the index labels using the argsort() function df = df[df.argsort()] # Lets print the sorted index labels. df |
Output :
Now we will find the latest label in the Index upto 72.
# find the latest index label upto 72 df.asof( 72 ) |
Output :
As we can see in the output, the function has returned the 69 as it is the previous index label which is smaller than 72.
Example #2: Use Index.asof()
function to find the label of index upto a given date.
# importing pandas as pd import pandas as pd # Creating the Index idx = pd.Index([ '2015-10-31' , '2015-12-02' , '2016-01-03' , '2016-02-08' , '2017-05-05' ]) # Print the Index df |
Output :
The index is already in the sorted order so we will not sort it.
Now we will apply the index.asof()
function to find the index label upto the input label.
# to find the label in the index upto '2016-01-01' idx.asof( '2016-01-01' ) |
Output :
As we can see in the output, the function has returned ‘2015-12-02’ date which is the previous date present in the Index up to ‘2016-01-01’