Python / Data Science Essentials Interview Questions
How do rolling and expanding window functions work in Pandas?
Window functions compute statistics over a sliding or expanding subset of rows, essential for time-series smoothing, trend detection, and feature engineering. Unlike groupby aggregations, window functions return a result for every row, preserving the original index.
import pandas as pd
import numpy as np
ts = pd.DataFrame({
'date': pd.date_range('2024-01-01', periods=10, freq='D'),
'sales': [100, 120, 90, 150, 200, 130, 110, 180, 160, 140],
})
ts = ts.set_index('date')
# --- Rolling window (fixed-size, slides one step at a time) ---
ts['ma3'] = ts['sales'].rolling(window=3).mean() # 3-day moving avg
ts['std3'] = ts['sales'].rolling(window=3).std()
ts['min3'] = ts['sales'].rolling(window=3).min()
# First window-1 values are NaN (not enough history)
# min_periods: require fewer observations before computing
ts['ma3_mp'] = ts['sales'].rolling(window=3, min_periods=1).mean()
# --- Expanding window (grows to include all rows so far) ---
ts['cum_max'] = ts['sales'].expanding().max()
ts['cum_mean'] = ts['sales'].expanding().mean()
# --- Exponentially weighted moving average (more weight on recent data) ---
ts['ewma'] = ts['sales'].ewm(span=3).mean()
# --- Lag / shift features (common in time-series forecasting) ---
ts['lag1'] = ts['sales'].shift(1) # yesterday's sales
ts['lag7'] = ts['sales'].shift(7) # last week's sales
ts['pct_change'] = ts['sales'].pct_change() # % change from previous rowMoving averages (rolling mean) smooth out noise to reveal trends. Exponentially weighted moving averages give more influence to recent observations, making them responsive to recent changes while still smoothing. Lag features turn a time-series prediction problem into a supervised learning problem where past values predict future ones.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
