Signup/Sign In

Pandas DataFrame last() Method

In this tutorial, we will learn the Python pandas DataFrame.last() method. This method can be used to select the final periods of time series data based on a date offset. When having a DataFrame with dates as the index, this method can select the last few rows based on a date offset. It returns the DataFrame and raises TypeError if the index is not a DatetimeIndex

The below shows the syntax of the DataFrame.last() method.

Syntax

DataFrame.last(offset)

Parameters

offset: It can be an str, DateOffset, or dateutil.relativedelta. The length of the data's offset will be selected. For example, ‘1M’ will display all the rows having their index within the first month.

Example: Getting the rows for the last n days using the DataFrame.last() Method

Here, we created a DataFrame with the DatetimeIdex as an index, we try to get the rows of the last 3 days using the DataFrame.last() method.

In the below example, the data for the last 3 calendar days were returned, not the last 3 days observed in the dataset, and therefore data for 2021-01-11 was not returned. See the below example.

#importing pandas as pd
import pandas as pd
i = pd.date_range('2021-01-09', periods=4, freq='2D')
df = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
print("The DataFrame is")
print(df)
print(df.last('3D'))


The DataFrame is
A
2021-01-09 1
2021-01-11 2
2021-01-13 3
2021-01-15 4
A
2021-01-13 3
2021-01-15 4

Example: Getting the rows for the last n days using the DataFrame.last() Method

This example is similar to the previous one. Here, in this example, we try to get the rows of the last 2 days using the DataFrame.last() method. See the below example.

#importing pandas as pd
import pandas as pd
i = pd.date_range('2021-01-09', periods=4, freq='4D')
df = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
print("The DataFrame is")
print(df)
print(df.last('2D'))


The DataFrame is
A
2021-01-09 1
2021-01-13 2
2021-01-17 3
2021-01-21 4
A
2021-01-21 4

Example: Getting the rows for the last n months using the DataFrame.last() Method

Here, in this example, we try to get the rows of the last 1 month using the DataFrame.last() method. See the below example.

#importing pandas as pd
import pandas as pd
i = pd.date_range('2021-01-01', periods=4, freq='1M')
df = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
print("The DataFrame is")
print(df)
print(df.last('1M'))


The DataFrame is
A
2021-01-31 1
2021-02-28 2
2021-03-31 3
2021-04-30 4
A
2021-04-30 4

Conclusion

In this tutorial, we learned the Python pandas DataFrame.last() method . We learned the syntax and applying this method to understand the DataFrame.last() method.



About the author:
I like writing about Python, and frameworks like Pandas, Numpy, Scikit, etc. I am still learning Python. I like sharing what I learn with others through my content.