Lesson
31: Pandas DataFrames β Vectorized Table Engineering Over
Slow iterrows() Loops
The βBoring Stuffβ Problem: Waiting Minutes on Excel Pivot Tables or Python Row Loops
When you have 527 daily plant telemetry logs
(39 columns in
UCI_Water_Treatment_Plant_Daily.csv) or
1,030 structural concrete recipes
(UCI_Concrete_LowCarbon_SCMs.csv),
spreadsheets turn fragile and slow.
Think of a Pandas DataFrame as a
programmable Excel table in RAM with labeled column headers
(df["DBO_E_mgL"]) and vectorized math that runs 100x faster
than looping row-by-row with .iterrows().
from pathlib import Path
def data_file(name):
"""Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
for p in [
Path("datasets") / name,
Path("../datasets") / name,
Path("../../datasets") / name,
]:
if p.exists():
return p
raise FileNotFoundError(f"Missing dataset {name} in datasets/")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Example 1 (Real UCI Urban Wastewater Treatment Plant Dataset β 527 Daily Operations!)
wt = pd.read_csv(data_file("UCI_Water_Treatment_Plant_Daily.csv"), na_values=["?"])
# Clean Date format "D-1/3/90" -> real Pandas timestamps
wt["ObsDate"] = pd.to_datetime(wt["Date"].str.replace("D-", "", regex=False), format="%d/%m/%y")
wt = wt.sort_values("ObsDate").set_index("ObsDate")
# Vectorized performance & daily mass load metrics (NO loops!)
wt["BOD_Load_In_kg_d"] = wt["Q_E_m3d"] * wt["DBO_E_mgL"] * 1e-3
wt["BOD_Load_Out_kg_d"] = wt["Q_E_m3d"] * wt["DBO_S_mgL"] * 1e-3
wt["Primary_SS_Rem_pct"] = (wt["SS_E_mgL"] - wt["SS_D_mgL"]) / wt["SS_E_mgL"] * 100.0
wt["Overall_BOD_Rem_pct"] = (wt["DBO_E_mgL"] - wt["DBO_S_mgL"]) / wt["DBO_E_mgL"] * 100.0
print("=== UCI Activated-Sludge WWTP Mass-Load & Stage Performance Audit ===")
print(wt[["Q_E_m3d", "BOD_Load_In_kg_d", "BOD_Load_Out_kg_d", "Primary_SS_Rem_pct", "Overall_BOD_Rem_pct"]].describe().round(2).loc[["count", "mean", "std", "min", "max"]])
fig, ax = plt.subplots(figsize=(8.0, 3.8))
ax.plot(wt.index, wt["DBO_E_mgL"], color="#d97706", alpha=0.65, lw=1.2, label="Raw Influent BOD5 [mg/L]")
ax.plot(wt.index, wt["DBO_S_mgL"], color="#059669", lw=1.6, label="Treated Effluent BOD5 [mg/L]")
ax.axhline(30.0, color="#dc2626", ls="--", lw=1.6, label="EPA Secondary Limit (30 mg/L)")
ax.set_title("Daily Municipal Wastewater BOD5 Removal (Real UCI Water Treatment Archive)")
ax.set_ylabel("BOD5 [mg/L]"); ax.grid(True, alpha=0.3); ax.legend(fontsize=8.5); fig.tight_layout()
=== UCI Activated-Sludge WWTP Mass-Load & Stage Performance Audit ===
Q_E_m3d BOD_Load_In_kg_d ... Primary_SS_Rem_pct Overall_BOD_Rem_pct
count 509.00 486.00 ... 525.00 496.00
mean 37226.57 6929.69 ... 53.83 88.78
std 6636.00 2357.63 ... 14.35 8.93
min 10050.00 1479.26 ... -14.81 -34.45
max 60081.00 17082.91 ... 96.71 96.98
[5 rows x 5 columns]
# Example 2 (LCA Track 1 Sustainable Materials): Embodied Carbon Proxy on 1,030 UCI Concrete Mixes
# Typical IPCC clinker emission factor ~0.85 kg CO2/kg cement vs SCM byproducts (~0.07 slag, ~0.02 fly ash)
conc = pd.read_csv(data_file("UCI_Concrete_LowCarbon_SCMs.csv"))
conc["Binder_kg_m3"] = conc["Cement_kg_m3"] + conc["BlastFurnaceSlag_kg_m3"] + conc["FlyAsh_kg_m3"]
conc["SCM_Share_pct"] = (conc["BlastFurnaceSlag_kg_m3"] + conc["FlyAsh_kg_m3"]) / conc["Binder_kg_m3"] * 100.0
conc["Est_CO2_kg_m3"] = 0.85 * conc["Cement_kg_m3"] + 0.07 * conc["BlastFurnaceSlag_kg_m3"] + 0.02 * conc["FlyAsh_kg_m3"]
conc["Strength_per_CO2"] = conc["CompressiveStrength_MPa"] / conc["Est_CO2_kg_m3"] * 1000.0
top_eco = conc[conc["Age_days"] == 28].sort_values("Strength_per_CO2", ascending=False).head(5)
print("\n=== Top-5 Low-Carbon Eco-Efficient Concrete Formulations (28-Day MPa per tonne CO2) ===")
print(top_eco[["Cement_kg_m3", "BlastFurnaceSlag_kg_m3", "FlyAsh_kg_m3", "SCM_Share_pct", "CompressiveStrength_MPa", "Est_CO2_kg_m3"]].round(1).to_string(index=False))=== Top-5 Low-Carbon Eco-Efficient Concrete Formulations (28-Day MPa per tonne CO2) ===
Cement_kg_m3 BlastFurnaceSlag_kg_m3 FlyAsh_kg_m3 SCM_Share_pct CompressiveStrength_MPa Est_CO2_kg_m3
141.9 166.6 129.7 67.6 44.6 134.9
142.0 167.0 130.0 67.7 44.6 135.0
275.0 180.0 120.0 52.2 76.2 248.8
165.0 128.5 132.1 61.2 46.4 151.9
250.0 180.0 95.0 52.4 67.9 227.0
Concept Check Questions
- Why should you NEVER write
for idx, row in df.iterrows(): df.loc[idx, "x"] = ...when vectorized column arithmetic (df["a"] * df["b"]) runs in one line? - Look at
top_eco: what industrial byproducts enabled concrete above45 MPawhile cutting embodied \(\text{CO}_2\) roughly in half compared to pure Portland cement mixes? - Why did we parse
wt["Date"].str.replace("D-", "")with explicit format"%d/%m/%y"?
Guided
Practice Problem 1: Filter High-COD Shock Load Days
(UCI_Water_Treatment_Plant_Daily.csv)
Filter wt for storm/industrial shock-load days where
both Q_E_m3d > 45000 AND
DQO_E_mgL > 500, then compute mean effluent
DBO_S_mgL and SS_S_mgL on shock days
vs.Β normal operating days!
# Guided Practice 1 Starter
shock = wt[(wt["Q_E_m3d"] > 45000) & (wt["DQO_E_mgL"] > 500)]
normal = wt[(wt["Q_E_m3d"] <= 45000) & (wt["DQO_E_mgL"] <= 500)]
print(f"Shock Days (n={len(shock)}): Mean BOD_out={shock['DBO_S_mgL'].mean():.1f}, Mean SS_out={shock['SS_S_mgL'].mean():.1f} mg/L")
print(f"Normal Days (n={len(normal)}): Mean BOD_out={normal['DBO_S_mgL'].mean():.1f}, Mean SS_out={normal['SS_S_mgL'].mean():.1f} mg/L")Shock Days (n=0): Mean BOD_out=nan, Mean SS_out=nan mg/L
Normal Days (n=334): Mean BOD_out=20.0, Mean SS_out=22.3 mg/L