S30 Logo
S30 AI Labwww.thes30.com
Back
#2

Pandas Lab

Easy🐍 Python & DataW1 D3

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.

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

SlowFast
df.apply(lambda row: ..., axis=1)Vectorized: df['a'] + df['b']
for idx, row in df.iterrows()df.groupby().agg()
String column with object dtypedf['col'].astype('category')
Repeated pd.concat in a loopCollect in list, concat once

Summary

ConceptKey Takeaway
GroupBySplit-apply-combine; use named agg for clean code
JoinsWatch for row explosion; always verify shape after merge
DateTimeUse .dt accessor, never apply() for date ops
Missing dataCheck .isna().sum() first; choose fill strategy based on domain
PerformanceVectorize 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?

Python 3 — Notebook
0/8 solvedSubstack Notes
1
Dataset & Setup

Pandas Lab — Student Notebook

Complete each # TODO cell. Run the checks to verify your work. Use Shift+Enter to run each cell.

Loading editor...
1

DataFrame Fundamentals

2
Filter purchases and extract event day
2

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')

Loading editor...
2

GroupBy

3
Build user-level features with groupby
2

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

Loading editor...
4
Row-level feature with transform
2

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')

Loading editor...
3

Joins & Merge

5
Left-join users with user_features
1

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)

Loading editor...
6
Diagnose and fix a many-to-many join explosion

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.

Loading editor...
4

Leakage-safe Time Features

7
Cumulative purchase count (strictly before current row)
1

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)

Loading editor...
5

Apply vs Vectorization

8
Compare apply vs vectorized boolean
2

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 u with many rows using pd.concat([users]*25000, ignore_index=True)
  • ●Vectorized: u['country'] == 'IN'
Loading editor...

Need help? Share feedback