Lesson 23: Reading Messy Real CSV Dialects & Exporting Clean Audited Reports (Pandas + csv)

The β€œBoring Stuff” Problem: European Semicolons (;), Comma Decimals (2,6) & ? Sentinels

When you open UCI_Air_Quality_Italy_Hourly.csv or UCI_Water_Treatment_Plant_Daily.csv in naive Excel or call pd.read_csv(file) with default arguments:

Calling pd.read_csv(..., sep=";", decimal=",", na_values=[-200, "-200", "-200,0"]) handles ALL of that cleanly in one line!

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 pandas as pd

# Example 1 (Real UCI Air Quality Dataset): Load 9,357 European-Format Rows Cleanly in 1 Call!
aq_raw = pd.read_csv(
    data_file("UCI_Air_Quality_Italy_Hourly.csv"),
    sep=";",
    decimal=",",
    na_values=[-200, -200.0, "-200", "-200,0"],
)
# Drop completely empty trailing Unnamed columns
aq = aq_raw.dropna(axis=1, how="all").copy()

print("=== Audited UCI Air Quality Dataset Columns & Missingness ===")
print(f"Shape: {aq.shape[0]:,} rows x {aq.shape[1]} columns")
completeness = (aq.notna().mean() * 100.0).round(1)
print(completeness[["CO(GT)", "C6H6(GT)", "NMHC(GT)", "NOx(GT)", "NO2(GT)", "T", "RH"]].to_string())
=== Audited UCI Air Quality Dataset Columns & Missingness ===
Shape: 9,357 rows x 15 columns
CO(GT)      82.0
C6H6(GT)    96.1
NMHC(GT)     9.8
NOx(GT)     82.5
NO2(GT)     82.5
T           96.1
RH          96.1
# Example 2 (Real UCI Wastewater Treatment Dataset): Handling '?' Missing Strings Cleanly
wt = pd.read_csv(data_file("UCI_Water_Treatment_Plant_Daily.csv"), na_values=["?"])
# Compute daily BOD and COD plant removal % directly from influent & effluent columns
wt["BOD_Rem_Calc_pct"] = (wt["DBO_E_mgL"] - wt["DBO_S_mgL"]) / wt["DBO_E_mgL"] * 100.0
wt["COD_Rem_Calc_pct"] = (wt["DQO_E_mgL"] - wt["DQO_S_mgL"]) / wt["DQO_E_mgL"] * 100.0

summary_cols = ["Q_E_m3d", "DBO_E_mgL", "DBO_S_mgL", "DQO_E_mgL", "DQO_S_mgL", "BOD_Rem_Calc_pct"]
print("=== Audited UCI Wastewater Treatment Telemetry (527 Days) ===")
print(wt[summary_cols].describe().round(2).loc[["count", "mean", "min", "50%", "max"]])
=== Audited UCI Wastewater Treatment Telemetry (527 Days) ===
        Q_E_m3d  DBO_E_mgL  DBO_S_mgL  DQO_E_mgL  DQO_S_mgL  BOD_Rem_Calc_pct
count    509.00     504.00     504.00      521.0     509.00            496.00
mean   37226.57     188.71      19.99      406.9      87.29             88.78
min    10050.00      31.00       3.00       81.0       9.00            -34.45
50%    35990.00     182.50      18.00      400.0      84.00             90.22
max    60081.00     438.00     320.00      941.0     350.00             96.98

Look how fast NMHC(GT) missingness (~9.8% complete = 90.2% dropped sensor!) popped right out in Example 1! Without programmatic completeness auditing, someone averaging -200 straight into spreadsheets gets completely nonsensical negative concentrations!


Concept Check Questions

  1. Look at Example 1: why did we call .dropna(axis=1, how="all") immediately after loading UCI_Air_Quality_Italy_Hourly.csv?
  2. What would wt["DBO_E_mgL"].mean() do if we forgot na_values=["?"]?
  3. Explain the difference between aq.dropna(axis=1, how="all") and aq.dropna(axis=0, how="any").

Guided Practice Problem 1: Filter High-Completeness Sensors & Inspect Valid Air Correlations

From aq above (UCI_Air_Quality_Italy_Hourly.csv), drop the failed NMHC(GT) column (< 20% complete), drop remaining NaN rows across ["CO(GT)", "C6H6(GT)", "NO2(GT)", "T", "RH"], and compute the Pearson correlation matrix (.corr()) to see how tightly roadside Benzene C6H6 tracks traffic Carbon Monoxide CO!

# Guided Practice 1 Starter
aq_sub = aq[["CO(GT)", "C6H6(GT)", "NO2(GT)", "T", "RH"]].dropna()
print(f"Complete clean urban air rows: {len(aq_sub):,}")
print(aq_sub.corr().round(3))
Complete clean urban air rows: 6,941
          CO(GT)  C6H6(GT)  NO2(GT)      T     RH
CO(GT)     1.000     0.930    0.674  0.018  0.065
C6H6(GT)   0.930     1.000    0.603  0.189 -0.022
NO2(GT)    0.674     0.603    1.000 -0.214 -0.075
T          0.018     0.189   -0.214  1.000 -0.564
RH         0.065    -0.022   -0.075 -0.564  1.000