{"slug":"python-air-quality-data-analysis-pandas","title":"Python for Air Quality Data Analysis: A Pandas Workflow","excerpt":"A working Python workflow for air quality monitoring data — parsing timestamps correctly, building a regular time index, applying capture rules, and producing the statistics compliance reporting actually needs.","date":"2026-08-27","author":"DSTechnoverse","image":"/blog-images/aq-stats/hero-air-quality-python-r.svg","category":"Air Quality Analysis","tags":["python air quality analysis","pandas air quality","air quality data python","PM2.5 analysis python","CAAQMS data analysis","air quality statistics","environmental data science"],"content":"Air quality data looks like a simple time series and behaves like nothing of the sort. It is skewed, gappy, seasonally driven, full of instrument artefacts, and governed by compliance rules that punish naive averaging.\n\nThis is a Python workflow that survives contact with real monitoring data.\n\n![Air quality analysis in R and Python](/blog-images/aq-stats/hero-air-quality-python-r.svg)\n\n## Why the Obvious Approach Fails\n\nThe instinctive first move is to load the CSV and take a mean. That produces a number, and the number is usually wrong, for reasons that compound:\n\n- Missing hours are silently skipped rather than counted, so a month with 40% data capture averages as though it were complete\n- Calibration and maintenance periods are averaged in as real measurements\n- Negative values from zero drift pull the mean down\n- The mean is reported where the standard asks for a 98th percentile\n- Duplicate hours from the daylight-saving transition are counted twice\n\nEvery one of these is invisible in the output. That is what makes them dangerous.\n\n## Step 1: Parse Timestamps Properly\n\nMore air quality analyses are wrong because of timestamps than because of statistics.\n\n```python\nimport pandas as pd\n\ndf = pd.read_csv('station_data.csv')\n\n# Be explicit about the format. Letting pandas infer will silently\n# swap day and month on ambiguous dates like 03/04/2025.\ndf['datetime'] = pd.to_datetime(df['datetime'], format='%d-%m-%Y %H:%M', errors='coerce')\n\n# Anything that failed to parse becomes NaT — count it, never ignore it.\nprint(f\"unparsed timestamps: {df['datetime'].isna().sum()}\")\n\ndf = df.dropna(subset=['datetime']).set_index('datetime').sort_index()\n```\n\nThree things worth knowing:\n\n**Set `format` explicitly.** Indian data is usually DD-MM-YYYY. Pandas may read it as MM-DD-YYYY for the first twelve days of each month and correctly thereafter, producing a dataset that is subtly wrong in a way no summary statistic reveals.\n\n**Use `errors='coerce'`, then count.** Silent failure is worse than loud failure.\n\n**Check for duplicates.** `df.index.duplicated().sum()` should be zero. If it is not, you have a clock or timezone problem to resolve before anything else.\n\n## Step 2: Build a Regular Time Index\n\nThis is the step that fixes the completeness problem at its root.\n\n```python\nfull_index = pd.date_range(df.index.min(), df.index.max(), freq='h')\ndf = df.reindex(full_index)\ndf.index.name = 'datetime'\n```\n\nMissing hours now exist as `NaN` rows. They are counted, visible, and impossible to accidentally exclude from a capture calculation.\n\n## Step 3: Apply Validity Flags and Range Checks\n\n```python\n# Instrument status codes to NaN — these are not measurements.\nINVALID = ['CAL', 'MAINT', 'ERR', 'OFF', 'DOWN']\nfor col in ['PM25', 'PM10', 'NO2', 'SO2', 'O3']:\n    flag = f'{col}_flag'\n    if flag in df.columns:\n        df.loc[df[flag].isin(INVALID), col] = pd.NA\n\n# Physically impossible values.\nLIMITS = {'PM25': (0, 1000), 'PM10': (0, 2000), 'NO2': (0, 500),\n          'SO2': (0, 500), 'O3': (0, 400)}\nfor col, (lo, hi) in LIMITS.items():\n    if col in df.columns:\n        df.loc[(df[col] < lo) | (df[col] > hi), col] = pd.NA\n\n# Cross-parameter sanity: PM2.5 is a subset of PM10.\nbad = df['PM25'] > df['PM10']\nprint(f\"PM2.5 > PM10 in {bad.sum()} hours\")\ndf.loc[bad, ['PM25', 'PM10']] = pd.NA\n```\n\nThat last check catches instrument problems nothing else will. PM2.5 physically cannot exceed PM10 — where it does, one of the two analysers is misbehaving.\n\n## Step 4: Aggregate With a Capture Rule\n\n![Cleaning air quality monitoring data](/blog-images/aq-stats/aq-data-cleaning-pipeline.svg)\n\nIndian and international practice generally requires **75% data capture** before a period may be reported.\n\n```python\ndef aggregate(series, freq, min_capture=0.75):\n    grouped = series.resample(freq)\n    means = grouped.mean()\n    capture = grouped.count() / grouped.size()\n    return means.where(capture >= min_capture), capture\n\ndaily, daily_capture = aggregate(df['PM25'], 'D')\nannual, annual_capture = aggregate(daily, 'YE')\n```\n\nTwo points that matter more than they look:\n\n**Aggregate in stages.** Hourly to daily, then daily to annual. Going straight from hourly to annual lets a few complete months stand in for a sparse year.\n\n**Return the capture rate alongside the value.** Reviewers will ask. A number without its capture rate is not defensible.\n\n## Step 5: The Statistics Compliance Actually Wants\n\n![Percentiles used in air quality compliance](/blog-images/aq-stats/aq-percentile-compliance.svg)\n\nNAAQS short-term standards are written as percentiles, not maxima:\n\n```python\ndef compliance_summary(daily, standard):\n    valid = daily.dropna()\n    return {\n        'n_days': len(valid),\n        'capture_pct': round(100 * len(valid) / len(daily), 1),\n        'annual_mean': round(valid.mean(), 1),\n        'p98': round(valid.quantile(0.98), 1),\n        'maximum': round(valid.max(), 1),\n        'exceedance_days': int((valid > standard).sum()),\n    }\n\nprint(compliance_summary(daily, standard=60))   # PM2.5 24-hour NAAQS\n```\n\nThe 98th percentile is the compliance figure for 24-hour standards. Reporting the maximum instead makes your site look worse than the standard judges it; reporting the mean makes it look better. Both are wrong.\n\nFor the arithmetic behind the index itself, see [how to calculate AQI in India](/blog/how-to-calculate-aqi-india).\n\n## Step 6: Diurnal and Weekly Patterns\n\n```python\nprof = df.assign(hour=df.index.hour, dow=df.index.dayofweek)\nby_hour = prof.groupby('hour')['PM25'].agg(['mean', 'median', 'count'])\nby_dow  = prof.groupby('dow')['PM25'].agg(['mean', 'median', 'count'])\n```\n\nThese carry real diagnostic weight. A morning and evening twin peak points to traffic. A flat overnight profile with a dawn rise suggests a boundary-layer effect rather than a source. A weekday–weekend difference confirms human activity as a driver.\n\nAlways carry `count` through. A striking pattern in an hour with eleven observations is not a pattern.\n\n## Step 7: Plot to Interrogate, Not to Decorate\n\n```python\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(3, 1, figsize=(11, 10))\ndaily.plot(ax=ax[0], lw=0.8, title='Daily mean PM2.5')\nax[0].axhline(60, color='crimson', ls='--', label='24-h NAAQS')\nax[0].legend()\n\nby_hour['mean'].plot(ax=ax[1], marker='o', title='Diurnal profile')\n\ndaily_capture.plot(ax=ax[2], title='Daily data capture', ylim=(0, 1.05))\nax[2].axhline(0.75, color='crimson', ls='--')\nplt.tight_layout()\n```\n\nThat third panel is the one most analysts omit and reviewers most want. Plotting capture over time immediately reveals whether your gaps are random or clustered in a particular season — and clustered gaps bias every statistic downstream.\n\n## Step 8: Multi-Station Work\n\nMost real projects involve several monitoring stations, and the shape of the data determines how painful it is.\n\nKeep station data in **long format** — one row per station, timestamp and parameter — rather than one wide column per station. Long format survives stations being added and removed mid-record, which wide format does not.\n\n```python\nlong = df.melt(id_vars=['datetime', 'station'],\n               value_vars=['PM25', 'PM10', 'NO2'],\n               var_name='parameter', value_name='value')\n\n# Capture and mean per station, per parameter, per year.\nsummary = (long\n    .set_index('datetime')\n    .groupby(['station', 'parameter'])['value']\n    .resample('YE')\n    .agg(['mean', 'count']))\n```\n\nThree cautions when comparing stations:\n\n**Equalise the period.** A station commissioned in March is not comparable with one running since January, and the difference will look like a concentration difference.\n\n**Compare capture before comparing values.** A station with poor winter capture will look cleaner than it is.\n\n**Check the site classification.** Kerbside, urban background, industrial and rural stations are not interchangeable. Comparing across classes without saying so is the most common error in multi-site reporting.\n\n## Reproducibility\n\nAnalyses get questioned months later, usually by someone who was not involved.\n\n**Script everything.** No manual edits to intermediate files — if a value changes, it should change because the code changed.\n\n**Keep the raw export untouched.** Read from it; never write back to it.\n\n**Version the cleaning rules.** When a threshold changes, the previously reported figures should still be reproducible.\n\n**Record library versions.** A `requirements.txt` or `environment.yml` costs nothing and prevents an unreproducible analysis two years on.\n\n**Emit the cleaning log as a file**, not as console output that disappears.\n\n## Common Python Mistakes\n\n| Mistake | Consequence |\n|---|---|\n| Letting pandas infer date format | Day/month swapped for part of the year |\n| `.dropna()` before computing capture | Completeness silently overstated |\n| `resample().mean()` with no capture rule | Sparse periods reported as if complete |\n| Aggregating hourly straight to annual | Missing months invisible |\n| Reporting mean where the standard says percentile | Wrong compliance conclusion |\n| Ignoring duplicated index entries | Some hours counted twice |\n| Treating zeros as valid | Zero drift pulls the mean down |\n\n## R or Python?\n\n![R and Python libraries for air quality work](/blog-images/aq-stats/aq-library-comparison.svg)\n\nBoth are entirely capable. The honest split:\n\n**R has openair**, a package built specifically for air quality that produces wind roses, polar plots, diurnal profiles and Theil-Sen trends in one line each. There is no direct Python equivalent, and for exploratory air quality work that is a real advantage.\n\n**Python has the better general ecosystem** — pandas for data handling, scikit-learn for modelling, and easier integration into production pipelines and web services.\n\nA common and sensible arrangement is Python for the data pipeline and R for exploratory air quality plotting. See [the openair package guide](/blog/r-openair-package-air-quality-guide).\n\n## Frequently Asked Questions\n\n**Which is better for air quality analysis, R or Python?** Both work. R's openair package is purpose-built for this domain and saves considerable time on exploratory plots. Python is stronger for pipelines and machine learning. Use what your team knows.\n\n**What data capture threshold should I use?** 75% is the widely applied minimum for reporting a period. Check the specific requirement for your regulator and standard, and always report the achieved capture rate alongside the value.\n\n**Why is my annual mean different from the regulator's?** Usually a capture rule, a validity flag treatment or a percentile-versus-mean difference. Reconcile the three before assuming an error.\n\n**How do I handle values below the detection limit?** A common convention is to substitute half the detection limit, but document whatever you do. Substitution choices materially affect low-concentration statistics.\n\n**Should I remove outliers?** Only those you can attribute to an instrument or a flag. A genuine pollution episode is data, not an outlier, and removing it is the most common way analyses understate exposure.\n\n**How do I test whether a change is real?** Use a trend test rather than comparing two annual means. See [air quality trend analysis methods](/blog/air-quality-trend-analysis-methods) and [the Mann-Kendall test](/blog/mann-kendall-test-air-quality).\n\n**Where do I get Indian monitoring data?** The [CPCB](https://cpcb.nic.in/) publishes CAAQMS data. See [CAAQMS data analysis](/blog/caaqms-data-analysis-india) for handling its particular quirks.\n\n---\n\n**Need air quality data analysed properly?** DSTechnoverse handles monitoring data QA/QC, statistical analysis, trend testing and compliance reporting in R and Python. We are based in **Indore, Madhya Pradesh** and work with clients across India. See our [air quality analysis](/services/air-quality-analysis) and [EIA data analysis outsourcing](/services/eia-data-analysis-outsourcing) services, or [talk to our team](/contact).","related":[{"slug":"air-quality-descriptive-statistics-percentiles","title":"Air Quality Statistics: Means, Percentiles and What Standards Require"},{"slug":"pm25-pm10-data-analysis","title":"PM2.5 and PM10 Data Analysis: From Raw Monitor Output to Defensible Insight"},{"slug":"air-quality-analysis-complete-guide","title":"Air Quality Analysis: The Complete Guide to Air Quality Data Analysis, Methods and Services"},{"slug":"air-quality-compliance-reporting-naaqs","title":"Air Quality Compliance Reporting Against NAAQS: Percentiles, Exceedances and Defensible Statistics"}]}