Pandas DataFrame asof() Method

In his tutorial, we will learn the python pandas DataFrame.asof() method. It returns the last row or rows without any NaNs before where. If the subset is not None, the last row without NaN considering only the subset of columns. If there is no good value, NaN is returned for a Series or a Series of NaN values for a DataFrame.

The below shows the syntax of DataFrame.asof() method.

Syntax

DataFrame.asof(where, subset=None)

Parameters

where: It represents the date or array-like of dates. Date(s) before which the last row(s) are returned.

subset: It represents the str or array-like of str, default None. For DataFrame, if not None, only use these columns to check for NaNs.

Example 1: Getting the last row using DataFrame.asof() Method

In the below example the DataFrame.asof() method returns the last rows of the specified sequence and the first value is NaN because the first element of the specified sequence is before the first index value.

import pandas as pd
import numpy as np
s = pd.DataFrame({'A':[1, 2, np.nan, 4],'B':[np.nan,2,np.nan,5.0]}, index=[10, 20, 30, 40])
print(s)
print(s.asof([5,20]))

Once we run the program we will get the following output.


A B
10 1.0 NaN
20 2.0 2.0
30 NaN NaN
40 4.0 5.0

A B
5 NaN NaN
20 2.0 2.0

Example 2: Missing values not considered when getting the last row

In the below example the DataFrame.asof() method returns the last rows of the specified sequence even though NaN is at the index location for 30.

import pandas as pd
import numpy as np
s = pd.DataFrame({'A':[1, 2, np.nan, 4],'B':[np.nan,2,np.nan,5.0]}, index=[10, 20, 30, 40])
print(s)
print(s.asof([10, 30]))

Once we run the program we will get the following output.


A B
10 1.0 NaN
20 2.0 2.0
30 NaN NaN
40 4.0 5.0
A B
10 NaN NaN
30 2.0 2.0

Example 3: Getting the last row using DataFrame.asof() Method

The below example shows the example of DataFrame.asof() method by considering a single column.

import pandas as pd
import numpy as np
s = pd.DataFrame({'A':[1, 2, np.nan, 4],'B':[np.nan,2,np.nan,5.0]}, index=[10, 20, 30, 40])
print(s)
print(s.asof([10,30],subset=['A']))

Once we run the program we will get the following output.


A B
10 1.0 NaN
20 2.0 2.0
30 NaN NaN
40 4.0 5.0
A B
10 1.0 NaN
30 2.0 2.0

Conclusion:

In this tutorial, we learned the python pandas DataFrame.asof() method. We learned the syntax, parameters and get the last rows of the DataFrame by solving examples.