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

PythonServer Side ProgrammingProgramming

To select first periods of time series based on a date offset, use the first() method. At first, set the date index with periods and freq parameters. 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 first 4 days i.e. 4D −

dataFrame.first('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...
",dataFrame # fetching initial few rows # fetch rows from the first 4 days print"First few rows fetched..
",dataFrame.first('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
First few rows fetched..
             k
2021-07-15   1
2021-07-18   2
raja
Updated on 16-Sep-2021 06:34:11

Advertisements