📜  Python| Pandas Series.last_valid_index()(1)

📅  最后修改于: 2023-12-03 15:04:22.004000             🧑  作者: Mango

Python | Pandas Series.last_valid_index()

The last_valid_index() function in the Pandas library is used to get the index label of the last non-null (valid) element in a Series. It returns the index label of the last valid element. This function can be very useful for finding the last available data point in a time-series dataset.

Syntax
Series.last_valid_index()
Parameters

This function does not take any parameters.

Return Value

The last_valid_index() function returns the index label of the last non-null (valid) element in the Series. If all elements are null, it returns NA. If the Series is empty, it returns None.

Example

Consider the following example to understand the usage of last_valid_index():

import pandas as pd

# Create a Series with some null values
data = pd.Series([1, 2, None, 4, None, 6, None])

# Get the index label of the last non-null element
last_index = data.last_valid_index()

print("Last non-null index:", last_index)

Output:

Last non-null index: 5

In the above example, we created a Series containing some null values. Using the last_valid_index() function, we obtained the index label of the last non-null element, which is 5 in this case.

Conclusion

The last_valid_index() function in Pandas is a convenient method to determine the index label of the last non-null value in a Series. It can be helpful for various data manipulation tasks, especially when working with time-series data.