Resampling, Rolling Windows & Shifting0%
Resampling, Rolling Windows & Shifting
Beginner12 min read•Updated: Jul 11, 2026
Resampling, Rolling Windows & Shifting
Reading Time: 8 Mins | Level: Beginner to Advanced
1. Time-Series Frequency Conversions (resample)
resample() is essentially a groupby() operation specifically for time-series data. It groups timestamps into discrete intervals (e.g., daily data into weekly, monthly, or quarterly summaries):
Python
import pandas as pd
import numpy as np
# Create daily sales data for 90 days
dates = pd.date_range(start='2026-01-01', periods=90, freq='D')
df = pd.DataFrame({
'Daily_Sales': np.random.randint(10000, 50000, size=90)
}, index=dates)
# Resample from Daily to Monthly Sums ('ME' = Month End)
monthly_sales = df.resample('ME').sum()
print("Monthly Revenue:\n", monthly_sales)
2. Rolling Window Calculations (Moving Averages)
In financial markets and business forecasting, daily metrics fluctuate wildly. A Rolling Moving Average smooths out noise to reveal underlying trends:
Python
# 7-Day Moving Average of Sales
df['7_Day_MA'] = df['Daily_Sales'].rolling(window=7).mean()
# 30-Day Rolling Standard Deviation (Volatility)
df['30_Day_Volatility'] = df['Daily_Sales'].rolling(window=30).std()
print(df.tail(10))
3. Shifting Data for Period-over-Period Growth (.shift)
To compute Day-over-Day or Month-over-Month growth, compare today's sales with yesterday's sales by shifting values down:
Python
# Shift values down by 1 row (yesterday's sales)
df['Prev_Day_Sales'] = df['Daily_Sales'].shift(1)
# Calculate Day-over-Day percentage change
df['DoD_Growth_Pct'] = (
(df['Daily_Sales'] - df['Prev_Day_Sales']) / df['Prev_Day_Sales']
) * 100
# Or use the built-in shortcut:
df['DoD_Growth_Shortcut'] = df['Daily_Sales'].pct_change() * 100
Interactive Quiz
Multiple Choice Questions
Question 1
Which method performs time-based frequency aggregation (e.g. converting hourly or daily records into monthly summaries)?
Question 2
What does
df['Sales'].rolling(window=7).mean() calculate?Question 3
What does
Series.shift(1) do?Question 4
Which built-in Pandas method directly computes the percentage change between the current and previous element?
Question 5
In modern Pandas, what frequency alias represents Month End in
resample()?Next Lesson
End-to-End Exploratory Data Analysis (EDA) Project
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| DateTime Parsing, Indexing & .dt Accessor | End-to-End Exploratory Data Analysis (EDA) Project |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.