MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Window Functions & Moving Averages in Pandas0%
Study MaterialsCheatsheet
Advanced Analytics & Machine LearningProgress 0%
1.1Downcasting Dtypes & Category Encoding for 10x Memory Savings1.2Method Chaining (pipe, assign) for Clean Production Pipelines1.3Window Functions & Moving Averages in Pandas1.4Modern Pandas 2.x/3.0: PyArrow Backend & Copy-on-Write
HomeTutorialsAdvanced Analytics & Machine LearningWindow Functions & Moving Averages in Pandas
Modern Pandas 2.x/3.0: PyArrow Backend & Copy-on-Write

Window Functions & Moving Averages in Pandas

Advanced7 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

In business intelligence and algorithmic finance, static metrics (like total monthly sales) hide critical intra-period dynamics. Window functions allow analysts to calculate moving averages, rolling volatility, cumulative totals, and exponential trends across temporal and partitioned sequences without collapsing the underlying dataset.


1. Rolling vs Expanding vs Exponential Windows

Window TypeMethodScope of CalculationTypical Use Case
Rolling Window.rolling(window=N)Fixed size $N$ past rows sliding forward7-day or 30-day Moving Averages
Expanding Window.expanding(min_periods=1)All historical rows up to current rowYear-To-Date (YTD) cumulative metrics
Exponential (EWM).ewm(span=N)Decaying weights giving recent data higher priorityTechnical analysis, algorithmic trading

2. Practical Rolling Calculations

To compute a rolling metric, ensure the DataFrame is sorted chronologically:

1import pandas as pd
2import numpy as np
3 
4# Ensure chronological sorting
5df = df.sort_values(by=['date']).reset_index(drop=True)
6 
7# 7-Day Simple Moving Average (SMA)
8df['revenue_7d_sma'] = df['revenue'].rolling(window=7, min_periods=1).mean()
9 
10# 30-Day Rolling Standard Deviation (Volatility indicator)
11df['revenue_30d_std'] = df['revenue'].rolling(window=30, min_periods=5).std()
12 
13# Rolling sum over 14 periods
14df['orders_14d_sum'] = df['orders'].rolling(window=14).sum()
Note
Note on min_periods: By default, .rolling(window=7) returns NaN for the first 6 rows. Setting min_periods=1 begins computing averages immediately from the first row.

3. Groupby with Rolling Windows (Partitioned Windows)

When analyzing metrics partitioned by entity (e.g., individual retail store branches, user accounts, or product categories), pair .groupby() with .rolling():

1# Compute 7-day rolling sales per store branch
2df['store_7d_avg'] = (
3 df
4 .groupby('store_id')['sales']
5 .rolling(window=7, min_periods=1)
6 .mean()
7 .reset_index(level=0, drop=True) # Drop the extra groupby index level
8)

4. Expanding Windows for Cumulative Insights

Expanding windows evaluate performance trajectory from the start of an experiment or fiscal period:

1# Cumulative Running Total (same as .cumsum(), but extensible to custom funcs)
2df['cumulative_revenue'] = df['revenue'].expanding(min_periods=1).sum()
3 
4# Running historical maximum drawdown baseline
5df['peak_historical_sales'] = df['revenue'].expanding().max()

5. Exponentially Weighted Moving Average (EWMA)

EWMA reacts faster to sudden changes than simple moving averages because recent observations receive exponentially higher weights:

1# 12-day Span Exponentially Weighted Moving Average
2df['ewma_12'] = df['revenue'].ewm(span=12, adjust=False).mean()

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does the min_periods parameter in df['sales'].rolling(window=7, min_periods=3).mean() do?
Question 2
How does an expanding window differ fundamentally from a rolling window?
Question 3
Why must a DataFrame be sorted chronologically before computing rolling metrics on time-series data?
Question 4
Which Pandas method calculates an exponentially weighted moving average where recent observations carry exponentially greater weight?
Question 5
What is the output of pd.Series([10, 20, 30]).expanding().mean()?

Next Lesson

Modern Pandas 2.x/3.0: PyArrow Backend & Copy-on-Write

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Method Chaining (pipe, assign) for Clean Production PipelinesModern Pandas 2.x/3.0: PyArrow Backend & Copy-on-Write

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

12-Month Data Analysis Mastery Program

Master Full-Stack Data Analytics (Excel, SQL, Python, Power BI & Tableau)

Combine 15 complete courses, 150 chapters, 541 topics, live SQL/Power BI/Tableau dashboards, and Scikit-Learn capstones at MSK Institute Shikohabad or Live Online.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext