Time Series Operations in Pandas

A collection of useful pandas snippets for time series analysis, including date filtering, period conversion, and merging by nearest match.

time series

Time Series Operations in Pandas

Handling time-series data efficiently is a core skill for data analysis. Whether you are filtering by year, converting to specific periods, or performing asynchronous joins, pandas provides a robust set of tools. Below are some common patterns and techniques, often encountered in database-style coding challenges.

Format change

to string: .dt.strftime(‘%Y-%m-%d’)

Leetcode 615: Average Salary: Departments VS Company

1. Date Filtering and Extraction

Extracting parts of a date or filtering by specific time components is frequent in reporting.


2. Advanced Merging and Analysis

1251. Average Selling Price

197. Rising Temperature

To compare a value with “yesterday’s” value, you can merge the table with itself using a calculated date offset.


3. Filtering by Aggregation

1084. Sales Analysis III

Sometimes you need to filter groups based on whether all their records fall within a certain range.

start_time = pd.to_datetime('2019-01-01')
end_time = pd.to_datetime('2019-03-31')

# Filter groups where the entire date range is within the window
df.groupby('product_id').filter(
    lambda x: x['sale_date'].min() >= start_time and x['sale_date'].max() <= end_time
)

This approach ensures that products sold strictly within the first quarter are selected, excluding any that had sales outside that period.