Module 03: Intermediate Pandas - Participation Exercises

Open In Colab

Module 03: Intermediate Pandas - Participation Exercises#

Exercise 3.1: Mini-Exercise - GroupBy Challenge#

Type: 🔧 Mini-Exercise (8 min)

Use groupby operations to answer questions about catalyst performance.

import pandas as pd
import numpy as np

np.random.seed(42)
df = pd.DataFrame({
    'catalyst': np.random.choice(['Pt/Al2O3', 'Pd/C', 'Ni/SiO2'], 150),
    'temperature': np.random.choice([350, 400, 450], 150),
    'yield': np.random.uniform(50, 95, 150),
    'selectivity': np.random.uniform(0.7, 0.99, 150)
})

# TASKS:
# 1. Find the mean yield for each catalyst
# 2. Find the mean yield for each catalyst-temperature combination
# 3. Which catalyst has the highest average selectivity?
# 4. Create a pivot table: rows=catalyst, columns=temperature, values=mean yield

# Your code here:

Exercise 3.2: Critique - Spot the Bug#

Type: 🔍 Critique (5 min)

The following code attempts to analyze experimental data but contains several bugs or poor practices. Find and fix them.

import pandas as pd
import numpy as np

# Sample data
df = pd.DataFrame({
    'temp': [350, 400, np.nan, 450, 400],
    'reaction_yield': [75, 82, 78, np.nan, 85],
    'catalyst': ['Pt', 'Pt', 'Pd', 'Pd', 'Pt']
})

# BUGGY CODE - Find the problems:

# Bug 1: Calculate mean yield per catalyst
mean_yields = df.groupby('catalyst').mean()['reaction_yield']

# Bug 2: Filter to high-yield experiments
high_yield = df[df.reaction_yield > 80]

# Bug 3: Fill missing temperatures with the mean
df.temp.fillna(df.temp.mean())

# Bug 4: Check if there are any missing values left
print("Missing values:", df.isnull().sum())

# What's wrong with each line? How would you fix it?
Missing values: temp              1
reaction_yield    1
catalyst          0
dtype: int64

Bugs identified:

  1. Bug 1:

  2. Bug 2:

  3. Bug 3:

  4. Bug 4: