{ "cells": [ { "cell_type": "markdown", "id": "e90de4ca", "metadata": {}, "source": [ "# 02 - Preprocessing" ] }, { "cell_type": "markdown", "id": "3cb9a2cf", "metadata": {}, "source": [ "## 1. Load & build datetime" ] }, { "cell_type": "code", "execution_count": 2, "id": "ba60a85a", "metadata": { "execution": { "iopub.execute_input": "2026-09-11T20:52:51.179569Z", "iopub.status.busy": "2026-09-11T20:52:51.179319Z", "iopub.status.idle": "2026-09-11T20:52:51.799332Z", "shell.execute_reply": "2026-09-11T20:52:51.798391Z" } }, "outputs": [ { "data": { "application/vnd.microsoft.datawrangler.viewer.v0+json": { "columns": [ { "name": "index", "rawType": "int64", "type": "integer" }, { "name": "No", "rawType": "int64", "type": "integer" }, { "name": "year", "rawType": "int64", "type": "integer" }, { "name": "month", "rawType": "int64", "type": "integer" }, { "name": "day", "rawType": "int64", "type": "integer" }, { "name": "hour", "rawType": "int64", "type": "integer" }, { "name": "PM2.5", "rawType": "float64", "type": "float" }, { "name": "PM10", "rawType": "float64", "type": "float" }, { "name": "SO2", "rawType": "float64", "type": "float" }, { "name": "NO2", "rawType": "float64", "type": "float" }, { "name": "CO", "rawType": "float64", "type": "float" }, { "name": "O3", "rawType": "float64", "type": "float" }, { "name": "TEMP", "rawType": "float64", "type": "float" }, { "name": "PRES", "rawType": "float64", "type": "float" }, { "name": "DEWP", "rawType": "float64", "type": "float" }, { "name": "RAIN", "rawType": "float64", "type": "float" }, { "name": "wd", "rawType": "str", "type": "string" }, { "name": "WSPM", "rawType": "float64", "type": "float" }, { "name": "station", "rawType": "str", "type": "string" }, { "name": "datetime", "rawType": "datetime64[us]", "type": "datetime" } ], "ref": "78dc2aea-ee9d-4921-85e4-927fd8146a81", "rows": [ [ "0", "173641", "2022", "8", "4", "0", "7.4", "11.6", "0.4", "2.0", "110.0", "28.0", "26.3", "1003.8", "25.0", "0.0", "SE", "3.68", "Barisal", "2022-08-04 00:00:00" ], [ "1", "173642", "2022", "8", "4", "1", "5.0", "8.1", "0.4", "2.0", "108.0", "28.0", "26.8", "1004.8", "24.8", "0.1", "SE", "3.7", "Barisal", "2022-08-04 01:00:00" ], [ "2", "173643", "2022", "8", "4", "2", "4.7", "7.5", "0.4", "2.1", "105.0", "28.0", "28.2", "1004.5", "25.0", "0.0", "SE", "4.56", "Barisal", "2022-08-04 02:00:00" ], [ "3", "173644", "2022", "8", "4", "3", "4.9", "7.7", "0.4", "2.1", "101.0", "29.0", "28.9", "1004.8", "25.1", "0.0", "SE", "4.2", "Barisal", "2022-08-04 03:00:00" ], [ "4", "173645", "2022", "8", "4", "4", "5.2", "8.1", "0.4", "1.7", "99.0", "32.0", "30.1", "1004.6", "25.4", "0.2", "SE", "4.18", "Barisal", "2022-08-04 04:00:00" ] ], "shape": { "columns": 19, "rows": 5 } }, "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NoyearmonthdayhourPM2.5PM10SO2NO2COO3TEMPPRESDEWPRAINwdWSPMstationdatetime
017364120228407.411.60.42.0110.028.026.31003.825.00.0SE3.68Barisal2022-08-04 00:00:00
117364220228415.08.10.42.0108.028.026.81004.824.80.1SE3.70Barisal2022-08-04 01:00:00
217364320228424.77.50.42.1105.028.028.21004.525.00.0SE4.56Barisal2022-08-04 02:00:00
317364420228434.97.70.42.1101.029.028.91004.825.10.0SE4.20Barisal2022-08-04 03:00:00
417364520228445.28.10.41.799.032.030.11004.625.40.2SE4.18Barisal2022-08-04 04:00:00
\n", "
" ], "text/plain": [ " No year month day hour PM2.5 PM10 SO2 NO2 CO O3 TEMP \\\n", "0 173641 2022 8 4 0 7.4 11.6 0.4 2.0 110.0 28.0 26.3 \n", "1 173642 2022 8 4 1 5.0 8.1 0.4 2.0 108.0 28.0 26.8 \n", "2 173643 2022 8 4 2 4.7 7.5 0.4 2.1 105.0 28.0 28.2 \n", "3 173644 2022 8 4 3 4.9 7.7 0.4 2.1 101.0 29.0 28.9 \n", "4 173645 2022 8 4 4 5.2 8.1 0.4 1.7 99.0 32.0 30.1 \n", "\n", " PRES DEWP RAIN wd WSPM station datetime \n", "0 1003.8 25.0 0.0 SE 3.68 Barisal 2022-08-04 00:00:00 \n", "1 1004.8 24.8 0.1 SE 3.70 Barisal 2022-08-04 01:00:00 \n", "2 1004.5 25.0 0.0 SE 4.56 Barisal 2022-08-04 02:00:00 \n", "3 1004.8 25.1 0.0 SE 4.20 Barisal 2022-08-04 03:00:00 \n", "4 1004.6 25.4 0.2 SE 4.18 Barisal 2022-08-04 04:00:00 " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "\n", "DATA_PATH = \"Bangladesh_Multi_Site_Air_Quality.csv\"\n", "\n", "df = pd.read_csv(\"../Bangladesh_Multi_Site_Air_Quality.csv\")\n", "df[\"datetime\"] = pd.to_datetime(df[[\"year\", \"month\", \"day\", \"hour\"]])\n", "df = df.sort_values([\"station\", \"datetime\"]).reset_index(drop=True)\n", "df.head()" ] }, { "cell_type": "markdown", "id": "f69d7a28", "metadata": {}, "source": [ "## 2. Check for missing hourly timestamps per station\\nEssential before building lag/rolling features - gaps would silently corrupt them." ] }, { "cell_type": "code", "execution_count": 3, "id": "d0f63a33", "metadata": { "execution": { "iopub.execute_input": "2026-09-11T20:52:51.801689Z", "iopub.status.busy": "2026-09-11T20:52:51.800890Z", "iopub.status.idle": "2026-09-11T20:52:51.824081Z", "shell.execute_reply": "2026-09-11T20:52:51.823311Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Checking for timestamp gaps per station...\n", " Barisal: 0 missing hourly timestamps out of 34728\n", " Chittagong: 0 missing hourly timestamps out of 34728\n", " Dhaka: 0 missing hourly timestamps out of 34728\n", " Khulna: 0 missing hourly timestamps out of 34728\n", " Rajshahi: 0 missing hourly timestamps out of 34728\n", " Sylhet: 0 missing hourly timestamps out of 34728\n" ] } ], "source": [ "print(\"Checking for timestamp gaps per station...\")\n", "for station, g in df.groupby(\"station\"):\n", " full_range = pd.date_range(g[\"datetime\"].min(), g[\"datetime\"].max(), freq=\"h\")\n", " missing = full_range.difference(g[\"datetime\"])\n", " print(f\" {station}: {len(missing)} missing hourly timestamps out of {len(full_range)}\")\n", "\n", "# NOTE: if gaps exist, reindex per station and interpolate, e.g.:\n", "# g = g.set_index(\"datetime\").reindex(full_range).interpolate(limit=3)\n", "# Not needed here since this dataset has none in practice." ] }, { "cell_type": "markdown", "id": "06329b3c", "metadata": {}, "source": [ "## 3. Duplicate check" ] }, { "cell_type": "code", "execution_count": 4, "id": "4600653e", "metadata": { "execution": { "iopub.execute_input": "2026-09-11T20:52:51.826023Z", "iopub.status.busy": "2026-09-11T20:52:51.825428Z", "iopub.status.idle": "2026-09-11T20:52:51.866695Z", "shell.execute_reply": "2026-09-11T20:52:51.865909Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Duplicate (station, datetime) rows: 0\n" ] } ], "source": [ "dupes = df.duplicated(subset=[\"station\", \"datetime\"]).sum()\n", "print(f\"Duplicate (station, datetime) rows: {dupes}\")\n", "df = df.drop_duplicates(subset=[\"station\", \"datetime\"])" ] }, { "cell_type": "markdown", "id": "4a5b332d", "metadata": {}, "source": [ "## 4. Outlier capping (winsorize)\n", "Cap pollutant/meteorological columns at the 1st/99th percentile **per station**.\n", "We deliberately do NOT touch PM2.5's upper tail - that's our real spike signal,\n", "capping it would destroy the thing we're trying to predict." ] }, { "cell_type": "code", "execution_count": 5, "id": "5d2ad6b5", "metadata": { "execution": { "iopub.execute_input": "2026-09-11T20:52:51.868593Z", "iopub.status.busy": "2026-09-11T20:52:51.868024Z", "iopub.status.idle": "2026-09-11T20:52:52.014298Z", "shell.execute_reply": "2026-09-11T20:52:52.013134Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Winsorizing done.\n" ] } ], "source": [ "cap_cols = [\"PM10\", \"SO2\", \"NO2\", \"CO\", \"O3\", \"WSPM\"]\n", "\n", "def winsorize_group(g):\n", " for col in cap_cols:\n", " lo, hi = g[col].quantile([0.01, 0.99])\n", " g[col] = g[col].clip(lo, hi)\n", " return g\n", "\n", "# NOTE: must pass df.columns explicitly - newer pandas groupby().apply()\n", "# silently drops the grouping column (\"station\") otherwise.\n", "df = df.groupby(\"station\", group_keys=False)[df.columns].apply(winsorize_group)\n", "\n", "non_negative_cols = [\"PM2.5\", \"PM10\", \"SO2\", \"NO2\", \"CO\", \"O3\", \"WSPM\", \"RAIN\"]\n", "for col in non_negative_cols:\n", " n_neg = (df[col] < 0).sum()\n", " if n_neg > 0:\n", " print(f\"WARNING: {n_neg} negative values in {col}, clipping to 0\")\n", " df[col] = df[col].clip(lower=0)\n", "print(\"Winsorizing done.\")" ] }, { "cell_type": "markdown", "id": "7c0248f5", "metadata": {}, "source": [ "## 5. Time-based train/test split\n", "**Important:** never split randomly for time series data - it leaks future\n", "information into training. Train = before 2026-01-01, Test = 2026 onward." ] }, { "cell_type": "code", "execution_count": 6, "id": "123134a6", "metadata": { "execution": { "iopub.execute_input": "2026-09-11T20:52:52.016723Z", "iopub.status.busy": "2026-09-11T20:52:52.015948Z", "iopub.status.idle": "2026-09-11T20:52:53.923444Z", "shell.execute_reply": "2026-09-11T20:52:53.922204Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Train: 179424 rows (2022-08-04 00:00:00 -> 2025-12-31 23:00:00)\n", "Test: 28944 rows (2026-01-01 00:00:00 -> 2026-07-20 23:00:00)\n", "Saved train_clean.csv and test_clean.csv\n" ] } ], "source": [ "SPLIT_DATE = \"2026-01-01\"\n", "train = df[df[\"datetime\"] < SPLIT_DATE].copy()\n", "test = df[df[\"datetime\"] >= SPLIT_DATE].copy()\n", "\n", "print(f\"Train: {train.shape[0]} rows ({train['datetime'].min()} -> {train['datetime'].max()})\")\n", "print(f\"Test: {test.shape[0]} rows ({test['datetime'].min()} -> {test['datetime'].max()})\")\n", "\n", "train.to_csv(\"train_clean.csv\", index=False)\n", "test.to_csv(\"test_clean.csv\", index=False)\n", "print(\"Saved train_clean.csv and test_clean.csv\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.3" } }, "nbformat": 4, "nbformat_minor": 5 }