What is DataFrame.last_valid_index in pandas?

Overview

The last_valid_index method is used to return the index for the last non-NA or None value. The method returns None for the following conditions:

  1. If all elements are non-NA or None.
  2. If the DataFrame is empty.

Note: Click here to learn more about the pandas library.

Syntax

DataFrame.last_valid_index()

Parameters

The method has no parameters.

Example

import pandas as pd
import numpy as np
def index(dataframe):
print("DataFrame is:")
print(dataframe)
print("Index of the last non-NA/null value is - ", dataframe.last_valid_index())
df = pd.DataFrame([[np.nan, np.nan, np.nan],[np.nan, 100,3],[1, 2, 3],[np.nan,-7,np.nan],[-9, -8, -7],[10, 8, 12]],columns=list('XYZ'))
df1 = pd.DataFrame([[np.nan, np.nan, np.nan],[np.nan, np.nan, np.nan],[np.nan, np.nan, np.nan],[np.nan,-3,np.nan],[10, 8, 12],[np.nan, np.nan, np.nan]],columns=list('XYZ'))
df2 = pd.DataFrame([[np.nan, np.nan, np.nan],[np.nan, np.nan, np.nan],[np.nan, np.nan, np.nan]],columns=list('XYZ'))
index(df)
index(df1)
index(df2)

Explanation

  • Lines 1–2: We import the pandas and numpy modules.
  • Lines 4–7: We define a function called index that accepts a data frame, prints it and finds the last non-NA/null value index using the last_valid_index method.
  • Lines 10–12: We define three different data frames with different patterns.
  • Lines 14–16: We call the index method with different DataFrames.

Output

  1. The output for df indicates that the 5th row has all values as non-NA/non-null from the end.
  2. The output for df1 indicates that the 4th row has all values as non-NA/non-null from the end.
  3. The output for df2 indicates that none of the rows have a non-null/non-NA value.

Free Resources