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

To select first periods of time series based on a date offset, use the first() method. This method filters rows from the beginning of a DataFrame up to a specified time period.

Creating a Time Series DataFrame

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

import pandas as pd

# Create date index with 5 periods and frequency of 3 days
i = pd.date_range('2021-07-15', periods=5, freq='3D')

# Create DataFrame with date index
dataFrame = pd.DataFrame({'k': [1, 2, 3, 4, 5]}, index=i)
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 first() Method

The first() method selects rows from the beginning based on a time offset ?

import pandas as pd

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

# Fetch rows from first 4 days
result = dataFrame.first('4D')
print("First few rows fetched...")
print(result)
First few rows fetched...
            k
2021-07-15  1
2021-07-18  2

Different Time Offsets

You can use various time offsets with the first() method ?

import pandas as pd

# Create sample data
dates = pd.date_range('2021-01-01', periods=10, freq='D')
df = pd.DataFrame({'value': range(10)}, index=dates)

print("Original DataFrame:")
print(df.head())

print("\nFirst 3 days:")
print(df.first('3D'))

print("\nFirst 1 week:")
print(df.first('1W'))
Original DataFrame:
            value
2021-01-01      0
2021-01-02      1
2021-01-03      2
2021-01-04      3
2021-01-05      4

First 3 days:
            value
2021-01-01      0
2021-01-02      1
2021-01-03      2

First 1 week:
            value
2021-01-01      0
2021-01-02      1
2021-01-03      2
2021-01-04      3
2021-01-05      4
2021-01-06      5
2021-01-07      6

Common Time Offset Aliases

Offset Description Example
'D' Days '5D' = 5 days
'W' Weeks '2W' = 2 weeks
'M' Months '3M' = 3 months
'H' Hours '12H' = 12 hours

Conclusion

The first() method is useful for selecting initial periods from time series data based on date offsets. It works with various time units like days, weeks, months, and hours for flexible data filtering.

Updated on: 2026-03-26T02:14:27+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements