
The asof method in pandas return the last row(s) without any NaNs before where.
syntax –
DataFrame.asof(where, subset=None)
where – date or array-like of dates. Date(s) before which the last row(s) are returned.
subset – The label of the columns to consider when checking for NaN
. By default, all columns are considered.
Examples –
Let’s read a dataset to work with.
import pandas as pd
import numpy as np
url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/fruit_prices.csv'
df = pd.read_csv(url)
df

Now, Let’s say that we want to find out the last row without any NaN before the 2nd row label (inclusive). To do that we can use the asof method in pandas.
df.asof(2)
#output
apple 89.0
Orange 46.0
Banana 26.0
Mango 292.0
Name: 2, dtype: float64
It’s the 0th row label as 1st and 2nd row labels contains NaNs.
Let’s check the last row without any NaNs before the 3rd row label (inclusive).
df.asof(3)
#output
apple 89.0
Orange 46.0
Banana 26.0
Mango 292.0
Name: 3, dtype: float64
It is again the 0th row label as the 3rd row label contain a single NaN value in the Mango column.
Now, Let’s check the last row label without any NaN values before the 4th row label (inclusive).
df.asof(4)
#output
apple 125.0
Orange 63.0
Banana 38.0
Mango 198.0
Name: 4, dtype: float64
This time it is the 4th row itself because this row does not contains any NaN values.