Garbage In, Wrong Footprint Out: How to Harmonize Mixed Activity Data for Carbon Forecasting
A practical Python pipeline using Pint, Median Absolute Deviation, and schema-enforced emission factor joins to clean messy ESG data.
Suppose you want to train a time-series model to forecast to forecast your company’s Scope 1 and Scope 2 greenhouse gas emissions. Suddenly the model forecast shoots up by 1000x in the middle of the year. What must have happened ?Is there something wrong in the manufacturing unit ?Did a manufacturing plant suddenly start burning ten times more fuel?
No. Someone in a regional office entered a monthly electricity bill in megawatt-hours (MWh) instead of kilowatt-hours (kWh).
In carbon accounting and ESG data science, almost every calculation comes down to one core formula:
Emissions (CO₂e) = Activity Data × Emission Factor
When data scientists build emissions forecasting models, it is tempting to jump straight to Prophet, SARIMA, or gradient-boosted trees. In practice, however, the accuracy of any carbon forecast depends far more on what happens before modeling begins. Corporate sustainability data arrives fragmented across utility PDFs, fleet fuel cards, ERP procurement ledgers, and facility spreadsheets—each using different units, regional standards, and naming quirks.
In this article, we will build an audit-ready unit harmonization pipeline in Python that normalizes mixed activity data, catches 1,000x unit slips before they corrupt your baseline, and safely joins records with versioned emission factor tables.
Why Unit Standardization Is Hard in ESG Data
Unlike clean sensor telemetry from a single IoT system, corporate activity data spans multiple physical dimensions and regional conventions:
• Electricity & Heating: Smart meters log kWh, while regional utility invoices arrive in MWh, GJ, therms, or CCF (hundred cubic feet).
• Fleet & Stationary Fuels: Fuel logs mix liters, US gallons, and Imperial gallons.
• Purchased Goods & Freight: Procurement ledgers vary between kg, lbs, metric tonnes (MT), and US short tons.
• Text & Formatting Chaos: Manual spreadsheet uploads introduce inconsistent labels like "kWh", "KWH", "kw-h", "Metric Ton", and "t".
If unstandardized activity tables are feeded into a forecasting model—or multiplied against emission factors whose denominators don't match—your model ends up learning accounting errors instead of real operational trends.
Architecture of the Harmonization Pipeline
Instead of maintaining fragile, hardcoded if/else multiplication dictionaries, a production-grade ESG preprocessing pipeline should enforce five sequential stages:
- Raw Lineage Preservation: Ingest raw values and units without overwriting source fields.
- Canonical String Mapping: Map free-text unit aliases to a controlled vocabulary.
- Dimensional & Domain Conversions: Use Pint (Python Library)for physical unit math and lookup tables for fuel calorific values.
- Scale-Slip Anomaly Detection: Use Median Absolute Deviation (MAD) to quarantine 100x/1,000x data-entry errors.
- Schema-Enforced Emission Factor Joins: Programmatically assert that activity units match emission factor denominators before multiplying.
Let’s walk through each step in Python.
Step 1: Ingest Raw Activity Data (and Keep Lineage)
Let’s create a sample pandas DataFrame representing messy operational inputs across multiple facilities. A golden rule in sustainability engineering is never overwrite raw inputs—third-party auditors will always ask to trace normalized figures back to the original utility bill.
PYTHON CODE
import numpy as np
import pandas as pd
import pint
# Initialize Pint's unit registry
ureg = pint.UnitRegistry()
raw_data = pd.DataFrame({
"facility_id": ["FAC-01", "FAC-01", "FAC-02", "FAC-03", "FAC-04", "FAC-05"],
"region": ["IN-WEST", "IN-WEST", "US-EAST", "IN-WEST", "GLOBAL", "EU-CENTRAL"],
"reporting_year":,
"activity_type": [
"electricity", "electricity", "natural_gas",
"diesel_fleet", "steel_purchased", "electricity"
],
"raw_value": [12500.0, 14.2, 450.0, 1200.0, 5.5, 9800.0],
"raw_unit": ["kWh", "MWh", "therms", "gal", "Metric Ton", "kw-h"]
})
Step 2: Normalize Free-Text Unit Aliases
Before running any unit math, map inconsistent free-text strings to a controlled canonical vocabulary (aligned with standards like QUDT or UN/CEFACT). If an unmapped unit string appears, the pipeline should raise an explicit error rather than silently skipping the row.
PYTHON CODE
UNIT_ALIASES = {
"kwh": "kilowatt_hour",
"kw-h": "kilowatt_hour",
"mwh": "megawatt_hour",
"therms": "therm",
"therm": "therm",
"gal": "US_liquid_gallon",
"gallons": "US_liquid_gallon",
"metric ton": "metric_ton",
"mt": "metric_ton",
"t": "metric_ton",
"lbs": "pound"
}
def clean_unit_string(unit_str: str) -> str:
cleaned = str(unit_str).strip().lower()
if cleaned not in UNIT_ALIASES:
raise ValueError(f"Unmapped unit encountered: '{unit_str}'")
return UNIT_ALIASES[cleaned]
raw_data["canonical_unit"] = raw_data["raw_unit"].apply(clean_unit_string)
Step 3: Dimensional & Fuel-Specific Conversions with Pint
Lets convert each activity category into a standardized target unit that aligns with our emission factor database (kilowatt_hour for energy/fuels and kilogram for purchased materials).
Using Pint gives us dimensional safety out of the box:
• Same-dimension conversions (MWh or therm → kilowatt_hour) happen automatically.
• Cross-dimension conversions (converting diesel volume in gallons to energy in kWh) require an explicit physical property lookup—specifically the fuel's Net Calorific Value (NCV). If someone tries to convert liters into kWh without a calorific lookup, Pint throws a DimensionalityError.
PYTHON CODE
TARGET_UNITS = {
"electricity": "kilowatt_hour",
"natural_gas": "kilowatt_hour",
"diesel_fleet": "kilowatt_hour",
"steel_purchased": "kilogram"
}
# Domain lookup: Net Calorific Value (NCV) for liquid fuels
# Example: Diesel NCV ≈ 9.94 kWh per liter
FUEL_ENERGY_DENSITY = {
"diesel_fleet": 9.94 * ureg.kilowatt_hour / ureg.liter
}
def standardize_row(row):
activity = row["activity_type"]
target_unit_str = TARGET_UNITS[activity]
quantity = row["raw_value"] * ureg(row["canonical_unit"])
target_unit = ureg(target_unit_str)
# Case 1: Same physical dimension (e.g., MWh -> kWh, Metric Ton -> kg)
if quantity.dimensionality == target_unit.dimensionality:
converted = quantity.to(target_unit)
# Case 2: Volume-to-Energy conversion using fuel calorific value
elif activity in FUEL_ENERGY_DENSITY and quantity.check("[volume]"):
energy_quantity = quantity * FUEL_ENERGY_DENSITY[activity]
converted = energy_quantity.to(target_unit)
# Case 3: Reject incompatible dimensions
else:
raise pint.DimensionalityError(
quantity.units, target_unit, extra_msg=f" for activity '{activity}'"
)
return pd.Series({
"standardized_value": round(converted.magnitude, 4),
"standardized_unit": target_unit_str
})
clean_df = pd.concat([raw_data, raw_data.apply(standardize_row, axis=1)], axis=1)
Use code with caution.
Step 4: Catching 1,000x Scale Slips Before Computing Emissions
Even when unit strings are valid, human data-entry errors happen—such as typing 14,200 into an upload template and selecting MWh from the dropdown instead of kWh. That single click inflates electricity consumption by 1,000x.
Why not use a standard Z-score to catch it? Because of the masking effect: a single 1,000x spike pulls the sample mean and standard deviation upward so dramatically that standard Z-scores often fail to flag the outlier.
Instead, group records by facility_id and activity_type, and use Median Absolute Deviation (MAD) alongside a ratio-to-median check:
PYTHON CODE
def flag_unit_scale_anomalies(df: pd.DataFrame, group_cols: list, value_col: str) -> pd.DataFrame:
df = df.copy()
group_median = df.groupby(group_cols)[value_col].transform("median")
abs_deviation = (df[value_col] - group_median).abs()
mad = abs_deviation.groupby([df[c] for c in group_cols]).transform("median")
# 0.6745 scales MAD to match standard deviation for normal distributions
df["modified_z_score"] = np.where(
mad > 0,
0.6745 * (df[value_col] - group_median) / mad,
0.0
)
df["median_ratio"] = df[value_col] / group_median
def classify_flag(row):
if row["median_ratio"] >= 500 or row["median_ratio"] <= 0.002:
return "CRITICAL: Suspected 1,000x unit slip"
elif abs(row["modified_z_score"]) > 3.5:
return "WARNING: Statistical anomaly - verify invoice"
return "OK"
df["qa_status"] = df.apply(classify_flag, axis=1)
return df
clean_df = flag_unit_scale_anomalies(
clean_df,
group_cols=["facility_id", "activity_type"],
value_col="standardized_value"
)
Step 5: Join with Versioned Emission Factors & Compute CO₂e
Finally, join your standardized activity table with a regional, year-specific Emission Factor (EF) reference table (such as CEA India, EPA eGRID, or UK DEFRA). By explicitly storing ef_denominator_unit in the lookup table, you turn unit verification into an automated assert check rather than a manual review.
PYTHON CODE
emission_factors = pd.DataFrame({
"activity_type": [
"electricity", "electricity", "electricity",
"natural_gas", "diesel_fleet", "steel_purchased"
],
"region": ["IN-WEST", "EU-CENTRAL", "US-EAST", "US-EAST", "IN-WEST", "GLOBAL"],
"reporting_year":,
"ef_value": [0.716, 0.230, 0.370, 0.181, 0.253, 1.850], # kg CO2e per unit
"ef_denominator_unit": [
"kilowatt_hour", "kilowatt_hour", "kilowatt_hour",
"kilowatt_hour", "kilowatt_hour", "kilogram"
],
"ef_source": [
"CEA_v20", "EEA_2025", "EPA_eGRID",
"EPA_2025", "DEFRA_2025", "WorldSteel_2025" ]
})
merged_df = pd.merge(
clean_df,
emission_factors,
on=["activity_type", "region", "reporting_year"],
how="left"
)
# Automated guardrails before calculating emissions
assert merged_df["ef_value"].notnull().all(), "Missing Emission Factor for one or more rows!"
assert (merged_df["standardized_unit"] == merged_df["ef_denominator_unit"]).all(), "Denominator unit mismatch!"
# Calculate emissions in metric tonnes of CO2e (tCO2e)
merged_df["emissions_t_co2e"] = ((merged_df["standardized_value"] * merged_df["ef_value"]) / 1000).round(4)
print(merged_df[[
"facility_id", "activity_type", "region",
"standardized_value", "standardized_unit",
"emissions_t_co2e", "ef_source"
]])
Running this pipeline produces a clean, traceable emissions table ready for monthly aggregation and time-series forecasting:
TEXT
facility_id activity_type region standardized_value standardized_unit emissions_t_co2e ef_source
0 FAC-01 electricity IN-WEST 12500.0000 kilowatt_hour 8.9500 CEA_v20
1 FAC-01 electricity IN-WEST 14200.0000 kilowatt_hour 10.1672 CEA_v20
2 FAC-02 natural_gas US-EAST 13188.2414 kilowatt_hour 2.3871 EPA_2025
3 FAC-03 diesel_fleet IN-WEST 45152.3858 kilowatt_hour 11.4236 DEFRA_2025
4 FAC-04 steel_purchased GLOBAL 5500.0000 kilogram 10.1750 WorldSteel_2025
5 FAC-05 electricity EU-CENTRAL 9800.0000 kilowatt_hour 2.2540 EEA_2025
Learnings from the above for ESG Data Pipelines
Building reliable emissions forecasts starts with disciplined data engineering. Before fitting any forecasting model to historical CO₂e series, make sure your pipeline enforces five rules:
- Preserve raw lineage: Always keep raw_value, raw_unit, and ef_source alongside normalized fields for auditability.
- Enforce physical dimensions: Use dimensional libraries like Pint instead of hardcoded conversion dictionaries so invalid conversions fail immediately.
- Separate physics from unit math: Keep fuel calorific values (NCV/GCV) and densities in versioned domain lookup tables.
- Quarantine scale slips: Use Median/MAD checks to intercept 100x and 1,000x unit slips before they distort seasonal baselines.
- Assert denominator parity: Programmatically verify that standardized_unit == ef_denominator_unit on every join.

Top comments (0)