Before You Start
- Required knowledge
- Python and NumPy basics; rows, columns, and table keys.
- Libraries used
- NumPy, pandas
- Dataset and source
- Toy users/events tables and duplicate-key examples created in the notebook.
- Expected output
- Filtered and aggregated tables, validated joins, cumulative features, and vectorization comparisons.
Lesson Videos
Pandas for AI/ML — Theory & Concepts
Read this before attempting the exercises. Pandas is the workhorse of data manipulation in ML pipelines. These notes cover what you need to know.
1. DataFrames: The Core Abstraction
A DataFrame is a 2D labeled data structure — think of it as a spreadsheet or SQL table in Python.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'user_id': [101, 102, 103],
'country': ['IN', 'US', 'CA'],
'revenue': [49.99, 0.0, 99.99]
})
user_id country revenue
0 101 IN 49.99
1 102 US 0.00
2 103 CA 99.99
Key properties:
- ●Index — row labels (default: 0, 1, 2, ...)
- ●Columns — named, typed (each column is a Series)
- ●dtypes — int64, float64, object (string), datetime64, category
Interview Tip: Always check df.dtypes and df.shape first. Many bugs come from unexpected types (e.g., numbers stored as strings).
2. Selection & Filtering
# Column selection
df['revenue'] # Series
df[['user_id', 'revenue']] # DataFrame
# Row filtering (boolean mask)
df[df['revenue'] > 0] # rows where revenue > 0
# .loc — label-based
df.loc[0, 'country'] # 'IN'
df.loc[df['country'] == 'US', 'revenue'] # revenue for US users
# .iloc — integer-based
df.iloc[0:2, 1:] # first 2 rows, columns from index 1 onward
FAANG Gotcha: .loc is inclusive on both ends. .iloc is exclusive on the end (like Python slicing).
3. GroupBy — Split-Apply-Combine
GroupBy is the most important Pandas operation for feature engineering.
# Count events per user
events.groupby('user_id').size()
# Multiple aggregations
user_features = events.groupby('user_id').agg(
n_events=('event', 'size'),
n_purchases=('event', lambda x: (x == 'purchase').sum()),
total_revenue=('amount', 'sum'),
)
Split: Apply: Combine:
+---------+ +----------+ +--------------+
| user=101| --sum()--> | rev=149 | --> | 101 | 149.98 |
| user=102| --sum()--> | rev=0 | | 102 | 0.00 |
| user=103| --sum()--> | rev=99 | | 103 | 99.99 |
+---------+ +----------+ +--------------+
Interview Tip: One groupby().agg() with named aggregations is idiomatic and avoids multiple passes over the data.
4. Joins & Merges
# Inner join (only matching keys)
merged = pd.merge(users, events, on='user_id', how='inner')
# Left join (keep all users, NaN for missing events)
merged = pd.merge(users, events, on='user_id', how='left')
Left Join:
users: events: result:
+----+----+ +----+-------+ +----+----+-------+
| 101| IN | | 101| view | | 101| IN | view |
| 102| US | | 101| buy | | 101| IN | buy |
| 103| CA | | 102| view | | 102| US | view |
+----+----+ +----+-------+ | 103| CA | NaN |
+----+----+-------+
FAANG Gotcha: Joins can explode row count if keys aren't unique. Always check: df.merge(...).shape vs expected.
5. DateTime Operations
df['signup_ts'] = pd.to_datetime(df['signup_ts'])
# Extract components
df['signup_ts'].dt.year
df['signup_ts'].dt.day_of_week # 0=Monday
df['signup_ts'].dt.floor('D') # truncate to day
# Time differences
df['days_since'] = (pd.Timestamp.now() - df['signup_ts']).dt.days
Key for ML: .dt operations are vectorized in C. Per-row parsing with apply() introduces Python overhead and is 10-100x slower.
6. Handling Missing Data
df.isna().sum() # count NaNs per column
df.dropna(subset=['revenue']) # drop rows with NaN revenue
df['revenue'].fillna(0) # fill NaN with 0
df['revenue'].fillna(df['revenue'].median()) # fill with median
Interview Tip: In ML, how you handle missing data matters. Options: drop, fill with mean/median, fill with a sentinel (-1), or use models that handle NaN natively (XGBoost).
7. Performance Tips
| Slow | Fast |
|---|---|
df.apply(lambda row: ..., axis=1) | Vectorized: df['a'] + df['b'] |
for idx, row in df.iterrows() | df.groupby().agg() |
String column with object dtype | df['col'].astype('category') |
Repeated pd.concat in a loop | Collect in list, concat once |
Summary
| Concept | Key Takeaway |
|---|---|
| GroupBy | Split-apply-combine; use named agg for clean code |
| Joins | Watch for row explosion; always verify shape after merge |
| DateTime | Use .dt accessor, never apply() for date ops |
| Missing data | Check .isna().sum() first; choose fill strategy based on domain |
| Performance | Vectorize everything; avoid iterrows() and apply(axis=1) |
Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!
Ready to practice?
Pandas Lab — Student Notebook
Complete each # TODO cell. Run the checks to verify your work.
Use Shift+Enter to run each cell.
DataFrame Fundamentals
Section 1 — DataFrame Fundamentals
Task 1.1: Filter purchases and extract event day
Filter events to only purchase rows, then create an event_day column by flooring event_ts to day.
HINT: Use events[events['event'] == 'purchase'] and .dt.floor('D')
GroupBy
Section 2 — GroupBy
Task 2.1: Build user-level features with groupby
Group events by user_id and compute:
- ●
n_events: count of events - ●
n_purchases: sum of purchase flags - ●
total_revenue: sum of amount
HINT: Use .assign() to create is_purchase, then .groupby().agg() with named aggregations
Task 2.2: Row-level feature with transform
Add a user_event_count column to events using transform('size') — this keeps the original row count.
HINT: groupby('user_id')['event'].transform('size')
Joins & Merge
Section 3 — Joins & Merge
Task 3.1: Left-join users with user_features
Merge users with user_features on user_id (left join). Fill NaN numeric columns with 0.
HINT: users.merge(user_features, on='user_id', how='left') then .fillna(0)
Task 3.2: Diagnose and fix a many-to-many join explosion
Join left and right on key k. Notice the row explosion. Fix it by deduplicating the right side first.
FAANG gotcha: Always validate row counts after joins to catch many-to-many explosions early.
Leakage-safe Time Features
Section 4 — Leakage-safe Time Features
Task 4.1: Cumulative purchase count (strictly before current row)
Sort events by user and time, compute cumulative purchase count, then shift by 1 so each row only sees past data.
FAANG gotcha: Using cumsum() without shift(1) leaks the current row's label into the feature.
HINT: groupby().cumsum() then groupby().shift(1).fillna(0)
Apply vs Vectorization
Section 5 — Apply vs Vectorization
Task 5.1: Compare apply vs vectorized boolean
Create country_is_in column two ways: with .apply(lambda) and with vectorized ==. Compare timing.
Use a larger DataFrame so timing is meaningful.
HINT:
- ●Build
uwith many rows usingpd.concat([users]*25000, ignore_index=True) - ●Vectorized:
u['country'] == 'IN'