Lesson 6 of 9
Relational Operations: GroupBy Aggregations, Window Functions & Merges
Feature engineering often requires aggregating transaction logs across entities: calculating 30-day customer spend averages, velocity metrics (failed logins in the last hour), and combining tables via SQL-style relational joins (`merge`). Writing vectorized Pandas GroupBy aggregations, window transforms, and merges without memory blowouts or unintended Cartesian products is an essential engineering skill.
High-Performance GroupBy Aggregations & Temporal Rolling Windows
import pandas as pd
import numpy as np
# Create relational transaction log
n_tx = 10_000
np.random.seed(42)
tx_df = pd.DataFrame({
'user_id': np.random.choice([f"U_{i:03d}" for i in range(100)], size=n_tx),
'timestamp': pd.date_range('2026-01-01', periods=n_tx, freq='10min'),
'amount': np.random.exponential(scale=50, size=n_tx),
'status': np.random.choice(['APPROVED', 'DECLINED'], size=n_tx, p=[0.95, 0.05])
})
# 1. MULTI-METRIC GROUPBY AGGREGATIONS WITH NAMED TUPLES
user_features = tx_df.groupby('user_id').agg(
total_spend=('amount', 'sum'),
avg_spend=('amount', 'mean'),
max_spend=('amount', 'max'),
std_spend=('amount', 'std'),
total_tx_count=('amount', 'count'),
declined_count=('status', lambda s: (s == 'DECLINED').sum())
).reset_index()
# Handle edge cases (users with 1 transaction have NaN standard deviation)
user_features['std_spend'] = user_features['std_spend'].fillna(0.0)
# 2. TEMPORAL ROLLING WINDOWS PER USER (Vectorized window aggregation)
# Calculate each user's rolling 1-hour transaction velocity
tx_df = tx_df.sort_values(['user_id', 'timestamp'])
tx_df['user_tx_last_hour'] = (
tx_df.groupby('user_id')
.rolling('1h', on='timestamp')['amount']
.count()
.values
)
# 3. RELATIONAL MERGE (LEFT JOIN) WITH VALIDATION CHECKS
# Enforce one-to-many relationship; raise error if customer table contains duplicate keys
enriched_tx = pd.merge(
tx_df,
user_features[['user_id', 'avg_spend', 'declined_count']],
on='user_id',
how='left',
validate='many_to_one' # Catches accidental duplicate rows
)
print(f"Enriched Transaction matrix shape: {enriched_tx.shape}")
print(enriched_tx[['user_id', 'timestamp', 'amount', 'user_tx_last_hour', 'avg_spend']].head(5))Pro Tip: Use `.transform()` for Broadcast Aggregations
When you need to normalize a row by its group statistic (e.g. `user_amount / user_avg_amount`), use `df['user_avg'] = df.groupby('user_id')['amount'].transform('mean')`. Unlike `.agg()`, `.transform()` returns an array with the exact same length as the original DataFrame, eliminating the need for a separate merge.
MlPandasGroupByMerge Visual Representation
Hands-On Challenge: Build a Customer RFM Feature Store
Using a simulated e-commerce purchase log, construct a pipeline that computes Recency (days since last purchase), Frequency (total count of orders), and Monetary Value (total revenue) per customer using pure vectorized Pandas GroupBy operations.
Quick Quiz & Key Concept Checks
Common Pitfall: GroupBy Aggregation Data Leakage in Time Series
Aggregating metrics across the entire dataset (e.g., calculating `user_lifetime_spend` using all historical rows) leaks future transaction totals into past training events. Always use expanding windows or cutoff timestamps to ensure aggregations only incorporate data available prior to the prediction timestamp.