Lesson 16: NumPy Vectorized Arrays, Boolean Masks & Real 43,824-Hour Airshed Analytics

The β€œBoring Stuff” Problem: Waiting on Python for Loops Over Millions of Grid Cells

Python lists are flexible (they can mix strings, floats, and tuples), which forces Python to check data types one item at a time inside a loop. A NumPy ndarray packs pure contiguous float64 C arrays in memory so C = Q / (np.pi * u * sy * sz) computes 50,000 points simultaneously in a single compiled CPU instruction!

Three Superpowers You Use Every Day

  1. Elementwise Vectorization: T_K = T_C + 273.15 converts an entire weather archive with NO for loop.
  2. Boolean Masking: valid = pm25[np.isfinite(pm25) & (pm25 >= 0)] filters missing values cleanly in one expression!
  3. Instant Environmental Percentiles: Regulatory air/water standards often target the 98th or 99th percentile (np.percentile(valid, 98)).
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 matplotlib.pyplot as plt

# Example 1 (Real 43,824-hr Beijing PM2.5 + Wind Speed Archive via NumPy!)
# Columns: 0=No,1=yr,2=mo,3=day,4=hr,5=pm2.5,6=DEWP,7=TEMP,8=PRES,9=cbwd,10=Iws,11=Is,12=Ir
raw_pm = np.genfromtxt(data_file("UCI_Beijing_PM25_Meteorology.csv"), delimiter=",", skip_header=1, usecols=(5, 7, 8, 10), missing_values="NA")
pm, temp_c, pres_hpa, wind_ms = raw_pm.T

valid_mask = np.isfinite(pm)
pm_clean = pm[valid_mask]
temp_clean = temp_c[valid_mask]
wind_clean = wind_ms[valid_mask]

print("=== NumPy Bulk Audit on 43,824 Beijing Hourly Records ===")
print(f"Valid PM2.5 Hours : {len(pm_clean):,} / {len(pm):,} ({len(pm_clean)/len(pm):.1%})")
print(f"Mean / Median     : {pm_clean.mean():.1f} / {np.median(pm_clean):.1f} ug/m^3")
print(f"90th / 98th / Max : {np.percentile(pm_clean, 90):.1f} / {np.percentile(pm_clean, 98):.1f} / {pm_clean.max():.1f} ug/m^3")
print(f"Mean PM2.5 Stagnant (W<=5) : {pm_clean[wind_clean <= 5.0].mean():.1f} vs Windy (W>20) : {pm_clean[wind_clean > 20.0].mean():.1f} ug/m^3")

fig, ax = plt.subplots(figsize=(7.6, 4.0))
ax.hist(np.clip(pm_clean, 0, 500), bins=45, color="#0284c7", alpha=0.82, edgecolor="white")
ax.axvline(35.0, color="#059669", ls="--", lw=2, label="WHO/EPA 24-h Ref (35 ug/m^3)")
ax.axvline(np.percentile(pm_clean, 98), color="#dc2626", ls=":", lw=2, label=f"98th Pct ({np.percentile(pm_clean,98):.0f} ug/m^3)")
ax.set_title("Beijing 5-Year Hourly PM2.5 Distribution (UCI Real Sensor Network)")
ax.set_xlabel("PM2.5 Concentration [ug/m^3] (clipped at 500)")
ax.set_ylabel("Hourly Count")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
NumPy Vectorized Arrays, Boolean Masks & Real 43,824-Hour Airshed Analytics Output Plot 1
=== NumPy Bulk Audit on 43,824 Beijing Hourly Records ===
Valid PM2.5 Hours : 41,757 / 43,824 (95.3%)
Mean / Median     : 98.6 / 72.0 ug/m^3
90th / 98th / Max : 221.0 / 366.0 / 994.0 ug/m^3
Mean PM2.5 Stagnant (W<=5) : 120.9 vs Windy (W>20) : 60.2 ug/m^3

Concept Check Questions

  1. Why did np.genfromtxt(..., missing_values="NA") automatically allow np.isfinite(pm) to isolate valid hours?
  2. Notice how high wind speeds (W > 20) cut mean \(\text{PM}_{2.5}\) sharply compared to stagnant air (W <= 5): explain the physical advection-dispersion mechanism (C ~ Q / u).
  3. Why does np.median stay much lower than pm_clean.mean() on right-skewed pollution histograms?

Guided Practice Problem 1: Cold-vs-Warm Air Pollution Inversion Vector Check

Using pm_clean and temp_clean above, compute the mean, median, and >150 ug/m^3 exceedance fraction separately for freezing inversion conditions (temp_clean < 0.0) versus warm convective days (temp_clean > 22.0).

# Guided Practice 1 Starter
cold = pm_clean[temp_clean < 0.0]
warm = pm_clean[temp_clean > 22.0]
print(f"Sub-zero (<0C)  : mean={cold.mean():.1f}, median={np.median(cold):.1f}, >150={(cold>150).mean():.1%}")
print(f"Warm (>22C)     : mean={warm.mean():.1f}, median={np.median(warm):.1f}, >150={(warm>150).mean():.1%}")
Sub-zero (<0C)  : mean=111.3, median=73.0, >150=26.9%
Warm (>22C)     : mean=90.5, median=77.0, >150=17.1%