Lesson
32: Complex Filtering, groupby().agg() & Multi-Site /
Ecotoxicity Tier Audits
The βBoring Stuffβ Problem: Building Multi-Metric Executive Tables From Thousands of Monitoring Rows
One groupby line replaces 500 lines of spreadsheet
filters:
summary = df.groupby("WindSector").agg(
Hours=("pm2.5", "count"),
Mean_PM25=("pm2.5", "mean"),
Pct95_PM25=("pm2.5", lambda s: s.quantile(0.95)),
)Letβs apply groupby + pd.cut
binning + multi-condition boolean masks directly across BOTH
43,824 hours of
UCI_Beijing_PM25_Meteorology.csv AND
UCI_QSAR_Aquatic_Toxicity.csv (LCA
Track 2 USEtox ecotoxicity classification)!
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 43,824-hr Beijing PM2.5 Multi-Year Air Quality): GroupBy Wind Direction + Season
bj = pd.read_csv(data_file("UCI_Beijing_PM25_Meteorology.csv"))
bj["Season"] = pd.cut(bj["month"], bins=[0, 2, 5, 8, 11, 12], labels=["Winter", "Spring", "Summer", "Autumn", "Winter"], ordered=False)
wind_summary = (
bj.dropna(subset=["pm2.5"])
.groupby("cbwd")
.agg(
Valid_Hours=("pm2.5", "count"),
Mean_PM25=("pm2.5", "mean"),
Median_PM25=("pm2.5", "median"),
Max_PM25=("pm2.5", "max"),
Mean_Wind_Iws=("Iws", "mean"),
)
.sort_values("Mean_PM25", ascending=False)
)
print("=== Beijing 5-Year PM2.5 Concentration by Wind Sector (`cbwd`) ===")
print(wind_summary.round(1).to_string())
season_tbl = bj.dropna(subset=["pm2.5"]).pivot_table(index="Season", columns="cbwd", values="pm2.5", aggfunc="mean")
print("\n=== Seasonal x Wind Direction Mean PM2.5 Matrix [ug/m^3] ===")
print(season_tbl.round(1).to_string())=== Beijing 5-Year PM2.5 Concentration by Wind Sector (`cbwd`) ===
Valid_Hours Mean_PM25 Median_PM25 Max_PM25 Mean_Wind_Iws
cbwd
cv 8944 126.2 98.0 980.0 2.2
SE 14573 110.8 91.0 845.0 18.5
NE 4756 90.2 55.0 852.0 7.8
NW 13484 70.1 31.0 994.0 49.7
=== Seasonal x Wind Direction Mean PM2.5 Matrix [ug/m^3] ===
cbwd NE NW SE cv
Season
Autumn 103.0 73.1 119.3 132.1
Spring 79.7 59.5 99.9 108.1
Summer 78.5 54.3 102.6 96.8
Winter 95.6 80.9 142.6 167.6
# Example 2 (Real UCI QSAR Aquatic Toxicity + LCA Track 2 Module 4 Link): Toxicity Binning via pd.cut
tox = pd.read_csv(data_file("UCI_QSAR_Aquatic_Toxicity.csv"))
tox["LogKow_Tier"] = pd.cut(
tox["MLOGP"],
bins=[-10.0, 1.0, 3.0, 4.5, 20.0],
labels=["Hydrophilic (<1)", "Moderate (1-3)", "Bioaccumulating (3-4.5)", "Very Lipophilic (>4.5)"],
)
tox_agg = tox.groupby("LogKow_Tier", observed=False).agg(
Chemicals=("LC50_neglog_molL", "count"),
Mean_NegLog_LC50=("LC50_neglog_molL", "mean"),
Pct_HighTox_gt5=("LC50_neglog_molL", lambda s: (s > 5.0).mean() * 100.0),
)
print("\n=== QSAR Ecotoxicity Escalation Across Log Kow Tiers (546 Industrial Chemicals) ===")
print(tox_agg.round(2).to_string())
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.2, 3.8))
wind_summary["Mean_PM25"].plot(kind="bar", ax=ax1, color=["#dc2626", "#f59e0b", "#0284c7", "#059669"], edgecolor="#0f172a")
ax1.set_title("Mean Beijing PM2.5 by Wind Direction"); ax1.set_ylabel("Mean PM2.5 [ug/m^3]"); ax1.tick_params(axis="x", rotation=0); ax1.grid(True, axis="y", alpha=0.3)
tox_agg["Mean_NegLog_LC50"].plot(kind="bar", ax=ax2, color="#7c3aed", edgecolor="#0f172a")
ax2.set_title("Acute Aquatic Toxicity (-log LC50) vs Lipophilicity"); ax2.set_ylabel("Mean -log10(LC50 [mol/L])"); ax2.tick_params(axis="x", rotation=15); ax2.grid(True, axis="y", alpha=0.3)
fig.tight_layout()
=== QSAR Ecotoxicity Escalation Across Log Kow Tiers (546 Industrial Chemicals) ===
Chemicals Mean_NegLog_LC50 Pct_HighTox_gt5
LogKow_Tier
Hydrophilic (<1) 123 3.41 16.26
Moderate (1-3) 224 4.46 27.68
Bioaccumulating (3-4.5) 150 5.38 54.67
Very Lipophilic (>4.5) 49 6.48 83.67
Look at BOTH real-world insights pulled cleanly in 15 lines of Pandas:
- Calm variable (
cv) and South-East (SE) urban winds push mean Beijing \(\text{PM}_{2.5}\) well above110 ug/m^3, while clean North-West (NW) continental gusts sweep \(\text{PM}_{2.5}\) down to~70 ug/m^3! - Raising chemical \(\log K_{ow}\)
(
MLOGP) from< 1to> 4.5raises mean fathead minnow aquatic toxicity by nearly 2 orders of magnitude (-log LC50jumps+1.9units =~80xmore lethal!).
Concept Check Questions
- Why did
pd.cut(bj["month"], ..., labels=["Winter", "Spring", "Summer", "Autumn", "Winter"], ordered=False)requireordered=Falsewhen grouping Dec (12) and JanβFeb (1β2) into"Winter"? - What does
.pivot_table(index="Season", columns="cbwd", values="pm2.5", aggfunc="mean")produce in one call? - Look at
named aggregationin.groupby("cbwd").agg(Mean_PM25=("pm2.5", "mean")): why is it cleaner than renaming multi-index tuples afterward?
Guided
Practice Problem 1: Gas Turbine NOx Grouping by Ambient Temperature Bin
(UCI_Gas_Turbine_2015_Emissions.csv)
Load UCI_Gas_Turbine_2015_Emissions.csv, bin ambient
temperature AT into
["Cold (<5C)", "Cool (5-15C)", "Warm (15-25C)", "Hot (>25C)"],
and compute groupby means of turbine power
TEY, CO, and NOX across all
7,384 hours!
# Guided Practice 1 Starter
gt_df = pd.read_csv(data_file("UCI_Gas_Turbine_2015_Emissions.csv"))
gt_df["Amb_Bin"] = pd.cut(gt_df["AT"], bins=[-20, 5, 15, 25, 50], labels=["Cold (<5C)", "Cool (5-15C)", "Warm (15-25C)", "Hot (>25C)"])
print(gt_df.groupby("Amb_Bin", observed=False)[["TEY", "CO", "NOX"]].agg(["count", "mean"]).round(2))TEY CO NOX
count mean count mean count mean
Amb_Bin
Cold (<5C) 522 140.43 522 4.17 522 74.17
Cool (5-15C) 2499 130.90 2499 4.17 2499 66.63
Warm (15-25C) 2905 132.07 2905 2.62 2905 54.68
Hot (>25C) 1458 140.82 1458 2.01 1458 53.61