01 · Data Cleaning and Integration

Objective. Combine the annual non-oil trade files published by the Information & eGovernment Authority (iGA) into a single, consistent record-level dataset covering January 2021 – September 2026.

Inputs. data/import/, data/export/ (domestic exports) and data/re-export/: one CSV per year or year range, with Arabic and English column headers that differ between releases.

Output. data/clean/bahrain_imports_exports.parquet, used by every subsequent notebook.

Procedure.

  1. Map each source's columns onto a common schema.
  2. Concatenate imports, domestic exports and re-exports.
  3. Recover missing country and commodity names from codes and Arabic names.
  4. Remove records whose trading partner cannot be identified, and records before 2021.
  5. Standardise text fields, build a monthly date, and assign each commodity an HS-section category.
%load_ext autoreload
%autoreload 2

import pandas as pd

from scripts.analysis import CLEAN_PARQUET
from scripts.cleaning_function import (
    clean_dirty,
    map_missing_names,
    map_missing_countries,
    map_missing_commodities,
)

1. Column mapping

The source files use different headers for the same field (Arabic in some years, English in others). The dictionaries below map every known header to the common schema: year, month, commodity_no, commodity_name, country_code, country_name, price_bhd, weight_kg, trade_type. Imports and exports differ only in the value/weight header wording.

common_mapping = {
    "السنة": "year",
    # commodity
    "Commodity No": "commodity_no",
    "Commodity": "commodity_name",
    "Commodity (Arabic)": "commodity_name",
    "السلعة": "commodity_ar_name",
    # country
    "UN code": "country_code",
    "الدولة": "country_ar_name",
    "أسم البلد": "country_name",
    "Country Name": "country_name",
}

imports_column_mapping = {
    **common_mapping,
    "قيمة الواردات (دينار بحريني)": "price_bhd",
    "وزن الواردات (كجم)": "weight_kg",
}

exports_column_mapping = {  # used for both domestic exports and re-exports
    **common_mapping,
    "قيمة الصادرات (دينار بحريني)": "price_bhd",
    "وزن الصادرات (كجم)": "weight_kg",
}

2. Load and standardise each source

clean_dirty() (in scripts/cleaning_function.py) renames the columns, converts Arabic month names to numbers and tags each record with its trade type. The 2024 import file has no year column, so the year is passed explicitly.

SOURCES = {
    "import": {
        "files": [
            "import/05-import-2021.csv",
            "import/04-import-2022.csv",
            "import/01-import-non-oil-classified-by-commodity-and-country-for-2023.csv",
            ("import/import-2024.csv", 2024),  # file has no year column
            "import/import-1-2025.csv",
            "import/import-2026.csv",
        ],
        "mapping": imports_column_mapping,
    },
    "export": {
        "files": [
            "export/02-national-export-2019-2022.csv",  # 2019-2020 removed in step 4
            "export/exports-national-origin-2023.csv",
            "export/national-export-1-2024.csv",
            "export/national-export-1-2025.csv",
            "export/exports-national-origin-2026.csv",
        ],
        "mapping": exports_column_mapping,
    },
    "re-export": {
        "files": [
            "re-export/kingdom-of-bahrain-re-export-non-oil-classified-by-commodity-and-country.csv",
            "re-export/re-export-2023.csv",
            "re-export/re-export-1-2024.csv",
            "re-export/re-export-1-2025.csv",
            "re-export/re-export-2026.csv",
        ],
        "mapping": exports_column_mapping,
    },
}

frames = []
for trade_type, spec in SOURCES.items():
    for entry in spec["files"]:
        file, year = entry if isinstance(entry, tuple) else (entry, None)
        raw = pd.read_csv(f"./data/{file}")
        frames.append(clean_dirty(raw, trade_type=trade_type, mappings=spec["mapping"], year=year))

df = pd.concat(frames, ignore_index=True)
print(f"Combined records: {len(df):,}")
df["trade_type"].value_counts()
Combined records: 2,194,755
trade_type
import       1806827
re-export     271866
export        116062
Name: count, dtype: int64

3. Recover missing names

Some releases provide only the code, others only the Arabic name. Missing English names are filled in two passes:

  1. Within the dataset. Look up the name used for the same code (or Arabic name) in another year.
  2. Manual mappings. Use the dictionaries in scripts/mappings.py for codes that never appear with an English name.
missing_before = df[["country_name", "commodity_name"]].isna().sum()

df = map_missing_names(df, "country_code", "country_name", "country_ar_name")
df = map_missing_names(df, "commodity_no", "commodity_name", "commodity_ar_name")
df = map_missing_commodities(df)
df = map_missing_countries(df)

missing_after = df[["country_name", "commodity_name"]].isna().sum()
pd.DataFrame({"missing_before": missing_before, "missing_after": missing_after})
missing_before missing_after
country_name 863406 1
commodity_name 386243 0

4. Remove unidentifiable and out-of-scope records

Records with no recoverable country cannot be attributed to a partner, so they are dropped. The study period starts in January 2021; the 2019–2020 rows in the combined export file are excluded.

n0 = len(df)
df = df[df["country_name"].notna()]
n1 = len(df)
df = df[df["year"] > 2020]
n2 = len(df)
df = df.drop(columns=["country_ar_name", "commodity_ar_name"], errors="ignore")

print(f"Dropped (no country):   {n0 - n1:,} ({(n0 - n1) / n0:.2%})")
print(f"Dropped (before 2021):  {n1 - n2:,}")
print(f"Remaining records:      {n2:,}")
print(f"Remaining missing values: {int(df.isna().sum().sum())}")
Dropped (no country):   1 (0.00%)
Dropped (before 2021):  44,276
Remaining records:      2,150,478
Remaining missing values: 0

5. Standardise fields and derive the date

Names are upper-cased so that the same partner or product spelt with different capitalisation is grouped together. A first-of-month date is built for time-series work.

df["commodity_name"] = df["commodity_name"].str.upper()
df["country_name"] = df["country_name"].str.upper()
df["date"] = pd.to_datetime({"year": df["year"], "month": df["month"], "day": 1})

6. Commodity categories (HS sections)

The first two digits of the 8-digit commodity code are the Harmonized System (HS) chapter. Chapters are grouped into 16 broad sections. Chapter 98 is a national code for special transactions. Earlier versions of this notebook left it uncategorised (4,244 records), so it now has its own label.

hs_chapter = (
    df["commodity_no"].astype("Int64").astype("string").str.zfill(8).str[:2].astype("Int64")
)

# Right-closed bins: (0, 5] -> chapters 1-5, (5, 15] -> 6-15, ...
bins = [0, 5, 15, 24, 27, 38, 40, 43, 49, 63, 67, 71, 83, 85, 89, 97, 99]
categories = [
    "Animal & Animal Products",        # 01-05
    "Vegetable Products",              # 06-15
    "Foodstuffs",                      # 16-24
    "Mineral Products",                # 25-27
    "Chemicals & Allied Industries",   # 28-38
    "Plastics / Rubbers",              # 39-40
    "Raw Hides, Skins, Leather, & Furs",  # 41-43
    "Wood & Wood Products",            # 44-49
    "Textiles",                        # 50-63
    "Footwear / Headgear",             # 64-67
    "Stone / Glass",                   # 68-71
    "Metals",                          # 72-83
    "Machinery / Electrical",          # 84-85
    "Transportation",                  # 86-89
    "Miscellaneous",                   # 90-97
    "Special Classification",          # 98-99 (national codes)
]
df["commodity_category"] = pd.cut(hs_chapter, bins=bins, labels=categories)

print("Uncategorised records:", df["commodity_category"].isna().sum())
Uncategorised records: 0

7. Save and verify

df.to_parquet(CLEAN_PARQUET, index=False)

clean = pd.read_parquet(CLEAN_PARQUET)
print(f"Saved {len(clean):,} records × {clean.shape[1]} columns")
print("Missing values:", int(clean.isna().sum().sum()))
clean.head()
Saved 2,150,478 records × 11 columns
Missing values: 0
year month commodity_no commodity_name country_code country_name price_bhd weight_kg trade_type date commodity_category
0 2021 1 1012910 HORSES FOR SPORT AE UNITED ARAB EMIRATES 6191.21240 4000.0 import 2021-01-01 Animal & Animal Products
1 2021 1 1012910 HORSES FOR SPORT GB UNITED KINGDOM 993.23300 2200.0 import 2021-01-01 Animal & Animal Products
2 2021 1 1012910 HORSES FOR SPORT IE IRELAND 967.98300 900.0 import 2021-01-01 Animal & Animal Products
3 2021 1 1012910 HORSES FOR SPORT US UNITED STATES OF AMERICA 708.24300 700.0 import 2021-01-01 Animal & Animal Products
4 2021 1 1022100 PURE-BRED BREEDING BOVINE NL NETHERLANDS 7826.02846 3050.0 import 2021-01-01 Animal & Animal Products
# Coverage: number of months available per year and trade type
clean.pivot_table(index="trade_type", columns="year", values="month", aggfunc="nunique")
year 2021 2022 2023 2024 2025 2026
trade_type
export 12 12 12 12 12 9
import 12 12 12 12 12 9
re-export 12 12 12 12 12 9

Summary

  • 2,194,755 raw records were combined from 16 source files: 1.81 M imports, 0.27 M re-exports and 0.12 M domestic exports.
  • Name recovery filled 863,405 of 863,406 missing country names and all 386,243 missing commodity names. Only one record had an unrecoverable partner and was removed.
  • 44,276 records from 2019–2020 were excluded, which leaves 2,150,478 records (Jan 2021 – Sep 2026) with no missing values.
  • Coverage is complete (12 months) for 2021–2025 for every trade type. 2026 covers January–September only, so any annual comparison must either exclude 2026 or compare the same months across years.
  • Assigning HS chapter 98 its own category removed all uncategorised records.