#!/usr/bin/env python3 """Example script for: Exporting PurpleAir Telemetry to GeoJSON and Pandas DataFrames Source: https://carlkidcrypto.github.io/blog/purpleair-api-geojson-pandas-export.html """ import json from typing import Any, Dict import pandas as pd def classify_pm25(pm25: float) -> str: if pm25 <= 9.0: return "Good" if pm25 <= 35.4: return "Moderate" if pm25 <= 55.4: return "USG" if pm25 <= 125.4: return "Unhealthy" if pm25 <= 225.4: return "Very Unhealthy" return "Hazardous" def dataframe_to_geojson(df: pd.DataFrame) -> Dict[str, Any]: features = [] for _, row in df.iterrows(): pm25 = float(row["pm2.5_atm"]) raw_conf = row.get("confidence") confidence = None if pd.isna(raw_conf) else raw_conf feature = { "type": "Feature", "geometry": { "type": "Point", # GeoJSON mandates [longitude, latitude] order "coordinates": [ float(row["longitude"]), float(row["latitude"]), ], }, "properties": { "sensor_index": int(row["sensor_index"]), "name": str(row.get("name", "Unknown")), "pm2_5_atm": round(pm25, 2), "aqi_category": classify_pm25(pm25), "confidence": confidence, }, } features.append(feature) return { "type": "FeatureCollection", "features": features, } def export_geojson(df: pd.DataFrame, output_path: str) -> None: collection = dataframe_to_geojson(df) with open(output_path, "w", encoding="utf-8") as fp: json.dump(collection, fp, indent=2) print(f"[+] Exported {len(collection['features'])} features.")