Lesson
12: Standard Library Toolkits (csv,
statistics, math) & Auditing Real UCI/LCA
CSVs cleanly
The “Boring Stuff” Problem: Manually Splitting Commas on Files With Quoted Descriptions
Wait—earlier we used row.split(",") on simple numeric
CSVs. Look what happens if a dataset contains a text description with a
comma inside quotes, such as "Carbon dioxide, fossil"
inside LCA1_System_LCI_Book_Matrix.csv or
HMT_Diffusivity_Henry_Solubility.csv!
Plain .split(",") splits right inside the quoted name and
shifts every column afterward!
Python’s built-in csv.DictReader parses
quoted commas automatically and turns every row into a clean dictionary
keyed by column header (row["Flow_Name"],
float(row["LC50_neglog_molL"])), while
statistics gives instant
mean, median, and stdev before
you even reach for Pandas.
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 csv
import statistics
# Example 1 (LCA Track 2 & Ecotoxicity): Auditing UCI_QSAR_Aquatic_Toxicity.csv via csv.DictReader + statistics
with data_file("UCI_QSAR_Aquatic_Toxicity.csv").open(encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
lc50_vals = []
lipophilic_lc50 = [] # MLOGP > 3.0 (high bioaccumulation potential!)
for row in reader:
lc50 = float(row["LC50_neglog_molL"])
mlogp = float(row["MLOGP"])
lc50_vals.append(lc50)
if mlogp > 3.0:
lipophilic_lc50.append(lc50)
print("=== UCI QSAR Aquatic Toxicity Summary (546 Industrial Chemicals) ===")
print(f"All Chemicals (N={len(lc50_vals)}) : mean -log(LC50) = {statistics.mean(lc50_vals):.3f}, median = {statistics.median(lc50_vals):.3f}, std = {statistics.stdev(lc50_vals):.3f}")
print(f"High-MLOGP (>3.0, N={len(lipophilic_lc50)}) : mean -log(LC50) = {statistics.mean(lipophilic_lc50):.3f} (Higher -log(LC50) = MORE TOXIC!)")=== UCI QSAR Aquatic Toxicity Summary (546 Industrial Chemicals) ===
All Chemicals (N=546) : mean -log(LC50) = 4.658, median = 4.516, std = 1.665
High-MLOGP (>3.0, N=199) : mean -log(LC50) = 5.652 (Higher -log(LC50) = MORE TOXIC!)
# Example 2 (LCA Track 1 Course Cross-Reference): Safe Quoted-CSV Parsing on LCA1_LCIA_Characterization_Factors.csv
with data_file("LCA1_LCIA_Characterization_Factors.csv").open(encoding="utf-8", newline="") as f:
cf_table = list(csv.DictReader(f))
print(f"Loaded {len(cf_table)} elementary LCIA Characterization Rows cleanly with csv.DictReader:")
for r in cf_table[:6]:
print(f" {r['Flow_ID']:<14s} | {r['Flow_Name']:<36s} | GWP100={float(r['GWP100_kgCO2eq']):6.1f} | AP={float(r['AP_kgSO2eq']):5.2f} | EP={float(r['EP_kgPO4eq']):5.2f}")Loaded 11 elementary LCIA Characterization Rows cleanly with csv.DictReader:
elem_co2_bio | Carbon dioxide (biogenic uptake) | GWP100= -1.0 | AP= 0.00 | EP= 0.00
elem_co2_fos | Carbon dioxide (fossil) | GWP100= 1.0 | AP= 0.00 | EP= 0.00
elem_co2 | Carbon dioxide (fossil) | GWP100= 1.0 | AP= 0.00 | EP= 0.00
elem_ch4 | Methane (fossil) | GWP100= 28.0 | AP= 0.00 | EP= 0.00
elem_n2o | Dinitrogen monoxide (N2O) | GWP100= 265.0 | AP= 0.00 | EP= 0.00
elem_so2 | Sulfur dioxide | GWP100= 0.0 | AP= 1.00 | EP= 0.00
Concept Check Questions
- What breaks if you use
.split(",")on a line containing"Soil, agricultural"inside quotes, and how doescsv.DictReaderprevent it? - Remember Higher
-log10(LC50)means LOWER lethal doseLC50(MORE toxic!): why do lipophilic organics (MLOGP > 3.0) show higher average-log(LC50)? - What does
if __name__ == "__main__":do when you put reusable environmental helpers inside your ownenv_tools.pyfile?
Guided
Practice Problem 1: Henry & Diffusivity Module Summary
(csv.DictReader + HMT)
Using csv.DictReader on
HMT_Diffusivity_Henry_Solubility.csv,
filter ONLY rows where Host_Medium_B == "Water", print each
gas species dissolving in water alongside its diffusivity
D_AB_m2_s and Schmidt number Sc, and compute
median D_AB across aqueous vs. gaseous pairs!
# Guided Practice 1 Starter
with data_file("HMT_Diffusivity_Henry_Solubility.csv").open(encoding="utf-8", newline="") as f:
hmt_rows = list(csv.DictReader(f))
water_d = [float(r["D_AB_m2_s"]) for r in hmt_rows if "Water" in r["Host_Medium_B"]]
air_d = [float(r["D_AB_m2_s"]) for r in hmt_rows if r["Host_Medium_B"] == "Air"]
print(f"Median Diffusivity in Air = {statistics.median(air_d):.2e} m^2/s vs Water = {statistics.median(water_d):.2e} m^2/s (~10,000x slower!)")Median Diffusivity in Air = 2.06e-05 m^2/s vs Water = 2.20e-09 m^2/s (~10,000x slower!)