
The last_valid_index() method in pandas returns the index of the last occurrence of a row containing a non-NaN
value. The check is performed row-wise, starting from the first row.
Syntax –
dataframe.last_valid_index()
Examples –
Let’s read a dataset to work with.
import pandas as pd
url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/fruit_prices.csv'
df = pd.read_csv(url)
df = df.head()
df

Now, Let’s say that you want to find the index of the last row that contains Non-NaN values. You can do this using the last_valid_index() method in pandas.
df.last_valid_index()
#output
4
Since the 4th row contains Non-NaN values, pandas return this row label as this is the index of the last row that contains Non-NaN values.
Now Let’s drop the 3rd and 4th rows.
df.drop([3, 4], inplace=True)

Now, Let’s find the last_valid_index()
df.last_valid_index()
#output
0
Since both 1st and 2nd row contains NaN values, the last row that contains Non-NaN values is the 0th row. That’s why pandas return 0th index.