Python Pandas - Select final periods of time series data based on a date offset

To select final periods of time series based on a date offset, use the last() method. This method allows you to extract the most recent data points within a specified time window from a datetime-indexed DataFrame.

Creating a Time Series DataFrame

First, create a date range with specific periods and frequency ?

import pandas as pd

# Create date index with 5 periods and frequency of 3 days
date_index = pd.date_range('2021-07-15', periods=5, freq='3D')
print("Date Index:")
print(date_index)
Date Index:
DatetimeIndex(['2021-07-15', '2021-07-18', '2021-07-21', '2021-07-24',
               '2021-07-27'],
              dtype='datetime64[ns]', freq='3D')

Creating DataFrame with DateTime Index

Now, create a DataFrame using the date index ?

import pandas as pd

date_index = pd.date_range('2021-07-15', periods=5, freq='3D')
dataFrame = pd.DataFrame({'k': [1, 2, 3, 4, 5]}, index=date_index)
print("DataFrame:")
print(dataFrame)
DataFrame:
            k
2021-07-15  1
2021-07-18  2
2021-07-21  3
2021-07-24  4
2021-07-27  5

Using last() Method

The last() method selects data from the final periods based on a date offset string ?

import pandas as pd

date_index = pd.date_range('2021-07-15', periods=5, freq='3D')
dataFrame = pd.DataFrame({'k': [1, 2, 3, 4, 5]}, index=date_index)

print("Original DataFrame:")
print(dataFrame)
print("\nLast 4 days:")
print(dataFrame.last('4D'))
Original DataFrame:
            k
2021-07-15  1
2021-07-18  2
2021-07-21  3
2021-07-24  4
2021-07-27  5

Last 4 days:
            k
2021-07-24  4
2021-07-27  5

Different Time Offsets

You can use various date offset strings with the last() method ?

import pandas as pd

date_index = pd.date_range('2021-07-15', periods=8, freq='2D')
dataFrame = pd.DataFrame({'value': range(1, 9)}, index=date_index)

print("Original DataFrame:")
print(dataFrame)
print("\nLast 7 days:")
print(dataFrame.last('7D'))
print("\nLast 2 weeks:")
print(dataFrame.last('2W'))
Original DataFrame:
            value
2021-07-15      1
2021-07-17      2
2021-07-19      3
2021-07-21      4
2021-07-23      5
2021-07-25      6
2021-07-27      7
2021-07-29      8

Last 7 days:
            value
2021-07-25      6
2021-07-27      7
2021-07-29      8

Last 2 weeks:
            value
2021-07-15      1
2021-07-17      2
2021-07-19      3
2021-07-21      4
2021-07-23      5
2021-07-25      6
2021-07-27      7
2021-07-29      8

Common Date Offset Strings

Offset String Description Example
'D' Days '5D' = Last 5 days
'W' Weeks '2W' = Last 2 weeks
'M' Months '3M' = Last 3 months
'Y' Years '1Y' = Last 1 year

Conclusion

The last() method is perfect for selecting recent time series data using intuitive date offset strings. It's particularly useful for financial data analysis and time-based filtering operations.

Updated on: 2026-03-26T02:13:30+05:30

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements