Exporting PurpleAir Telemetry to GeoJSON and Pandas DataFrames¶
Note
Published: December 1, 2026
Authors: Written by Gemini 3.8 Flash, Co-Authored & Reviewed by Carlos Santos (@carlkidcrypto)
Estimated Reading Time: 7 minutes
Tags: PurpleAir • Python • GeoJSON • Pandas • GIS • Air Quality • Open Source
Raw responses from the PurpleAir REST API are optimized for compact network
transmission rather than immediate spatial analysis. When you query a
geographic region with purpleair_api (published on PyPI as
purpleair-api), the API returns
parallel arrays: a fields header list and a nested data matrix of
values.
Before plotting smoke plumes in QGIS, rendering interactive Leaflet web maps, or running statistical regressions, you need to transform those raw arrays into standard analytical formats: Pandas DataFrames and RFC 7946 GeoJSON FeatureCollections.
In this tutorial, we will fetch regional sensor telemetry using
PurpleAirReadAPI, normalize rows into typed Pandas DataFrames, compute
EPA PM2.5 AQI categories, and serialize valid GeoJSON for GIS pipelines.
Understanding PurpleAir’s Tabular JSON Payload¶
Both request_multiple_sensors_data() and request_members_data() return
a JSON dictionary structured like this:
{
"fields": ["sensor_index", "name", "latitude", "longitude", "pm2.5_atm"],
"data": [
[282168, "Moscow Downtown", 46.7324, -117.0002, 12.4],
[175420, "Pullman Campus", 46.7319, -117.1542, 14.1]
]
}
Notice two key GIS details:
Coordinate Ordering:
PurpleAir returns
latitudefollowed bylongitude, whereas RFC 7946 GeoJSON strictly requires[longitude, latitude](X, Y order).
Null Handling:
Offline or indoor-only stations may omit optional fields such as
temperatureorpm2.5_atm, returningNoneinsidedatarows. Always filter or coerce nulls before running spatial math.
Loading Bounding-Box Telemetry into Pandas¶
Using PurpleAirReadAPI.request_multiple_sensors_data(), we can pull all
outdoor sensors within a geographic bounding box directly into a typed
pandas.DataFrame:
import os
import pandas as pd
from purpleair_api.PurpleAirAPIError import PurpleAirAPIError
from purpleair_api.PurpleAirReadAPI import PurpleAirReadAPI
QUERY_FIELDS = [
"sensor_index",
"name",
"latitude",
"longitude",
"pm2.5_atm",
"temperature",
"humidity",
"confidence",
]
def fetch_region_dataframe(
read_key: str,
nwlng: float,
nwlat: float,
selng: float,
selat: float,
) -> pd.DataFrame:
client = PurpleAirReadAPI(api_read_key=read_key)
try:
payload = client.request_multiple_sensors_data(
fields=",".join(QUERY_FIELDS),
nwlng=nwlng,
nwlat=nwlat,
selng=selng,
selat=selat,
location_type=0, # Outdoor sensors only
max_age=3600, # Active within the last hour
)
except PurpleAirAPIError as err:
print(f"[-] PurpleAir API request failed: {err}")
return pd.DataFrame(columns=QUERY_FIELDS)
fields = payload.get("fields", [])
rows = payload.get("data", [])
df = pd.DataFrame(rows, columns=fields)
# Drop stations missing valid coordinates or PM2.5 readings
df = df.dropna(subset=["latitude", "longitude", "pm2.5_atm"]).copy()
# Ensure numeric dtypes for downstream calculations
numeric_cols = ["latitude", "longitude", "pm2.5_atm", "humidity"]
for col in numeric_cols:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
return df
if __name__ == "__main__":
key = os.environ["PURPLEAIR_READ_KEY"]
# Inland Northwest / Palouse bounding box
df_palouse = fetch_region_dataframe(
read_key=key,
nwlng=-117.35,
nwlat=46.85,
selng=-116.85,
selat=46.60,
)
print(f"[+] Loaded {len(df_palouse)} outdoor sensors:")
print(df_palouse[["name", "pm2.5_atm", "confidence"]].head())
Serializing DataFrames to RFC 7946 GeoJSON¶
Once cleaned in Pandas, converting the DataFrame into a GeoJSON
FeatureCollection takes just a few lines of pure Python—no heavy C spatial
libraries required:
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.")
Spatial & Analytical Best Practices¶
Filter by ``confidence`` Before Interpolation:
When generating kriging or inverse-distance-weighted (IDW) smoke heatmaps, filter
df[df["confidence"] >= 80]so a single fouled optical chamber does not distort an entire county’s interpolation surface.
Use ``request_members_data()`` for Fixed Monitoring Networks:
When tracking a curated list of municipal or university stations, query your sensor group via
request_members_data(group_id=..., fields=...)and feed the response into the exact samepd.DataFrame(rows, columns=fields)normalizer.
Keep Coordinate Precision Reasonable:
Rounding coordinates to 5 decimal places (~1.1 m resolution) keeps GeoJSON payloads compact when serving live dashboards over mobile networks.
Summary & What’s Next¶
Transforming purpleair_api responses into typed Pandas DataFrames and RFC 7946 GeoJSON unlocks rapid spatial mapping, smoke plume modeling, and GIS integration with minimal code.
In our next blog post, we will rotate to purpleair_data_logger, exploring automated database schema migrations and version upgrades with Alembic so TimescaleDB pipelines evolve cleanly without downtime.
Warning
AI-generated content may contain misinformation or mistakes. A human does review this, but we are only human.