 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to retrieve the last valid index from a series object using pandas series.last_valid_index() method?
The pandas series.last_valid_index() method is used to get the index of the last valid element from the given series object. This means the last_valid_index() method returns the index of the last non_null element of the series.
It will return a single scalar based on the type of series index, and it will return None if the given series has all null/NA values or if it is empty. The method doesn’t have any parameters.
Example 1
Let’s create a pandas series object and retrieve the last valid index by using the last_valid_index() method.
# importing packages import pandas as pd import numpy as np # create a series s = pd.Series([None, 34, np.nan, 87], index=list('pqrs')) print(s) # apply last_valid_index() method result = s.last_valid_index() print("Result:") print(result)  Output
The output is as follows −
p NaN q 34.0 r NaN s 87.0 dtype: float64 Result: s
For the above example, the last valid index is “s”, because the element at index position s is not a Null/NA value.
Example 2
Here, let’s take an empty series object and see how the last_valid_index() method works for an empty series.
# importing packages import pandas as pd # create an empty series sr = pd.Series([]) print(sr) # apply last_valid_index() method result = sr.last_valid_index() print("Result:") print(result)  Output
The output is mentioned below −
Series([], dtype: float64) Result: None
The last_valid_index() method returned None for the empty series object.
Example 3
In this following example, we have created a pandas series object with all Null/Nan values and applied the last_valid_index() method to get the last valid index.
# importing packages import pandas as pd import numpy as np # create a series sr = pd.Series([None, np.nan]) print(sr) # apply last_valid_index() method result = sr.last_valid_index() print("Result:") print(result)  Output
The output is given below −
0 NaN 1 NaN dtype: float64 Result: None
For this example, the last_valid_index() method returned None, because there is no valid element available in the given series object.
