Home/Blog/Python for Air Quality Data Analysis: A Pandas Workflow
Back to Blog

Python for Air Quality Data Analysis: A Pandas Workflow

August 27, 2026
8 min read
By DSTechnoverse
Air Quality Analysis

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.

Python for Air Quality Data Analysis: A Pandas Workflow

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.

This is a Python workflow that survives contact with real monitoring data.

Why the Obvious Approach Fails

The 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:

  • Missing hours are silently skipped rather than counted, so a month with 40% data capture averages as though it were complete
  • Calibration and maintenance periods are averaged in as real measurements
  • Negative values from zero drift pull the mean down
  • The mean is reported where the standard asks for a 98th percentile
  • Duplicate hours from the daylight-saving transition are counted twice

Every one of these is invisible in the output. That is what makes them dangerous.

Step 1: Parse Timestamps Properly

More air quality analyses are wrong because of timestamps than because of statistics.

import pandas as pd

df = pd.read_csv('station_data.csv')

# Be explicit about the format. Letting pandas infer will silently
# swap day and month on ambiguous dates like 03/04/2025.
df['datetime'] = pd.to_datetime(df['datetime'], format='%d-%m-%Y %H:%M', errors='coerce')

# Anything that failed to parse becomes NaT — count it, never ignore it.
print(f"unparsed timestamps: {df['datetime'].isna().sum()}")

df = df.dropna(subset=['datetime']).set_index('datetime').sort_index()

Three things worth knowing:

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.

Use errors='coerce', then count. Silent failure is worse than loud failure.

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.

Step 2: Build a Regular Time Index

This is the step that fixes the completeness problem at its root.

full_index = pd.date_range(df.index.min(), df.index.max(), freq='h')
df = df.reindex(full_index)
df.index.name = 'datetime'

Missing hours now exist as NaN rows. They are counted, visible, and impossible to accidentally exclude from a capture calculation.

Step 3: Apply Validity Flags and Range Checks

# Instrument status codes to NaN — these are not measurements.
INVALID = ['CAL', 'MAINT', 'ERR', 'OFF', 'DOWN']
for col in ['PM25', 'PM10', 'NO2', 'SO2', 'O3']:
    flag = f'{col}_flag'
    if flag in df.columns:
        df.loc[df[flag].isin(INVALID), col] = pd.NA

# Physically impossible values.
LIMITS = {'PM25': (0, 1000), 'PM10': (0, 2000), 'NO2': (0, 500),
          'SO2': (0, 500), 'O3': (0, 400)}
for col, (lo, hi) in LIMITS.items():
    if col in df.columns:
        df.loc[(df[col] < lo) | (df[col] > hi), col] = pd.NA

# Cross-parameter sanity: PM2.5 is a subset of PM10.
bad = df['PM25'] > df['PM10']
print(f"PM2.5 > PM10 in {bad.sum()} hours")
df.loc[bad, ['PM25', 'PM10']] = pd.NA

That last check catches instrument problems nothing else will. PM2.5 physically cannot exceed PM10 — where it does, one of the two analysers is misbehaving.

Step 4: Aggregate With a Capture Rule

Cleaning air quality monitoring data

Indian and international practice generally requires 75% data capture before a period may be reported.

def aggregate(series, freq, min_capture=0.75):
    grouped = series.resample(freq)
    means = grouped.mean()
    capture = grouped.count() / grouped.size()
    return means.where(capture >= min_capture), capture

daily, daily_capture = aggregate(df['PM25'], 'D')
annual, annual_capture = aggregate(daily, 'YE')

Two points that matter more than they look:

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.

Return the capture rate alongside the value. Reviewers will ask. A number without its capture rate is not defensible.

Step 5: The Statistics Compliance Actually Wants

Percentiles used in air quality compliance

NAAQS short-term standards are written as percentiles, not maxima:

def compliance_summary(daily, standard):
    valid = daily.dropna()
    return {
        'n_days': len(valid),
        'capture_pct': round(100 * len(valid) / len(daily), 1),
        'annual_mean': round(valid.mean(), 1),
        'p98': round(valid.quantile(0.98), 1),
        'maximum': round(valid.max(), 1),
        'exceedance_days': int((valid > standard).sum()),
    }

print(compliance_summary(daily, standard=60))   # PM2.5 24-hour NAAQS

The 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.

For the arithmetic behind the index itself, see how to calculate AQI in India.

Step 6: Diurnal and Weekly Patterns

prof = df.assign(hour=df.index.hour, dow=df.index.dayofweek)
by_hour = prof.groupby('hour')['PM25'].agg(['mean', 'median', 'count'])
by_dow  = prof.groupby('dow')['PM25'].agg(['mean', 'median', 'count'])

These 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.

Always carry count through. A striking pattern in an hour with eleven observations is not a pattern.

Step 7: Plot to Interrogate, Not to Decorate

import matplotlib.pyplot as plt

fig, ax = plt.subplots(3, 1, figsize=(11, 10))
daily.plot(ax=ax[0], lw=0.8, title='Daily mean PM2.5')
ax[0].axhline(60, color='crimson', ls='--', label='24-h NAAQS')
ax[0].legend()

by_hour['mean'].plot(ax=ax[1], marker='o', title='Diurnal profile')

daily_capture.plot(ax=ax[2], title='Daily data capture', ylim=(0, 1.05))
ax[2].axhline(0.75, color='crimson', ls='--')
plt.tight_layout()

That 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.

Step 8: Multi-Station Work

Most real projects involve several monitoring stations, and the shape of the data determines how painful it is.

Keep 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.

long = df.melt(id_vars=['datetime', 'station'],
               value_vars=['PM25', 'PM10', 'NO2'],
               var_name='parameter', value_name='value')

# Capture and mean per station, per parameter, per year.
summary = (long
    .set_index('datetime')
    .groupby(['station', 'parameter'])['value']
    .resample('YE')
    .agg(['mean', 'count']))

Three cautions when comparing stations:

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.

Compare capture before comparing values. A station with poor winter capture will look cleaner than it is.

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.

Reproducibility

Analyses get questioned months later, usually by someone who was not involved.

Script everything. No manual edits to intermediate files — if a value changes, it should change because the code changed.

Keep the raw export untouched. Read from it; never write back to it.

Version the cleaning rules. When a threshold changes, the previously reported figures should still be reproducible.

Record library versions. A requirements.txt or environment.yml costs nothing and prevents an unreproducible analysis two years on.

Emit the cleaning log as a file, not as console output that disappears.

Common Python Mistakes

MistakeConsequence
Letting pandas infer date formatDay/month swapped for part of the year
.dropna() before computing captureCompleteness silently overstated
resample().mean() with no capture ruleSparse periods reported as if complete
Aggregating hourly straight to annualMissing months invisible
Reporting mean where the standard says percentileWrong compliance conclusion
Ignoring duplicated index entriesSome hours counted twice
Treating zeros as validZero drift pulls the mean down

R or Python?

R and Python libraries for air quality work

Both are entirely capable. The honest split:

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.

Python has the better general ecosystem — pandas for data handling, scikit-learn for modelling, and easier integration into production pipelines and web services.

A common and sensible arrangement is Python for the data pipeline and R for exploratory air quality plotting. See the openair package guide.

Frequently Asked Questions

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.

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.

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.

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.

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.

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 and the Mann-Kendall test.

Where do I get Indian monitoring data? The CPCB publishes CAAQMS data. See CAAQMS data analysis for handling its particular quirks.


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 and EIA data analysis outsourcing services, or talk to our team.

Share

Tags

python air quality analysispandas air qualityair quality data pythonPM2.5 analysis pythonCAAQMS data analysisair quality statisticsenvironmental data science

Explore More Articles

Discover more insights and updates from DSTechnoverse

View All Articles