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. At first, set the date index with periods and freq. Freq is for frequency −

i = pd.date_range('2021-07-15', periods=5, freq='3D')

Now, create a DataFrame with above index −

dataFrame = pd.DataFrame({'k': [1, 2, 3, 4, 5]},index=i) 

Fetch rows from last 4 days i.e. 4D −

dataFrame.last('4D')

Example

Following is the complete code −

import pandas as pd # date index set with 5 periods and frequency of 3 days i = pd.date_range('2021-07-15', periods=5, freq='3D') # creating DataFrame with above index dataFrame = pd.DataFrame({'k': [1, 2, 3, 4, 5]}, index=i) print"DataFrame...\n",dataFrame # fetching last few rows # fetch rows from last 4 days print"Last few rows fetched..\n",dataFrame.last('4D');

Output

This will produce the following output −

DataFrame...              k 2021-07-15   1 2021-07-18   2 2021-07-21   3 2021-07-24   4 2021-07-27   5 Last few rows fetched..              k 2021-07-24 4 2021-07-27 5
Updated on: 2021-09-15T13:17:10+05:30

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements