Skip to main content
BIG DATA ANALYTICS WITH PYTHON
ENSEA, Abidjan, Côte d’Ivoire · 30 November – 4 December 2026
<span style="background: #F2A65A; color: #14213D; font-weight: 700; font-size: 13px; padding: 4px 10px; border-radius: 12px;">Module 0 · Python Foundations for Data Work</span>
<span style="background: #D7E6E4; color: #14213D; font-weight: 600; font-size: 13px; padding: 4px 10px; border-radius: 12px; margin-left: 6px;">⏱ about 10 minutes</span>

Check your setup

Objective Confirm that your laptop is ready for the course before Day 2
You will Check Python and the bda environment · Check the course packages and Java · Run Spark · Check the datasets from the USB drive
Data The four datasets in data/raw/ (about 24 GB, USB drive)
Core packages pyspark · pandas

Run this notebook after creating the bda environment in the Python environment setup and copying the datasets from the USB drive.

How to run it: run this notebook in your browser with jupyter lab, as described in Step 7a of the setup guide. Choose Run → Run All Cells. It takes a minute or two.

Each check prints ✅ if it passed, or ❌ with a one-line fix and a link to the relevant part of the guides. Section 6 tells you whether you’re ready.

# Core: system, file and package checks
import importlib
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

# PySpark is imported inside the Spark cells (sections 4 and 7), not here, so that this
# notebook still runs and tells you what to fix when PySpark is missing.

0. Setup and Configuration

Working Directory and Input Files

# ============================================================
# BASE WORKING DIRECTORIES
# ============================================================
# This notebook sits in notebooks/00-intro-to-python/, so the course folder is two levels up
DIR_COURSE = Path.cwd().parents[1]
DIR_DATA = DIR_COURSE / "data" / "raw"

# ============================================================
# INPUT FILES (COPIED FROM THE USB DRIVE)
# ============================================================
# Synthetic call detail records (folder of about 10,000 CSV files)
DIR_CDRS = DIR_DATA / "synthetic-cdrs"

# Cell tower locations
FILE_CELL_LOCS = DIR_DATA / "synthetic-cell-locs.csv"

# Large activity log
FILE_ACTIVITY_LOG = DIR_DATA / "activity_log_raw.csv"

# Census microdata subset (pipe-separated)
FILE_HH_DATA = DIR_DATA / "hh-data-ml.csv"

Global Variables for Processing

# ============================================================
# LINKS TO THE SETUP GUIDES
# ============================================================
GUIDES = "https://worldbank.github.io/BDA-with-Python/docs/guides/"
SETUP_ENV = GUIDES + "python-environment.html#step-4"
BROWSER = GUIDES + "python-environment.html#test-your-installation"
RUN_IN_BROWSER = (
    "Run this notebook in the browser (Step 7a): in your terminal, `conda activate bda`, go to the "
    "course folder, then `jupyter lab`."
)
TROUBLESHOOT = GUIDES + "python-environment.html#troubleshooting"
WINDOWS_SPARK = GUIDES + "python-environment.html#windows-spark"
DATASETS = GUIDES + "datasets.html"

# On Windows, Java, Spark and Hadoop problems are fixed by Step 5 of the setup guide
IS_WINDOWS = platform.system() == "Windows"
SPARK_HELP = WINDOWS_SPARK if IS_WINDOWS else TROUBLESHOOT
WINDOWS_FIX = (
    "Do Step 5 of the setup guide (set up Spark for Windows), close and reopen VS Code or "
    "JupyterLab, then run this notebook again."
)

# ============================================================
# REQUIRED VERSIONS AND PACKAGES
# ============================================================
MIN_PYTHON = (3, 10)
MIN_JAVA = 17
ENV_NAME = "bda"

# Import name -> name to show (the pip/conda package name where it differs)
PACKAGES = {
    "pandas": "pandas",
    "numpy": "numpy",
    "matplotlib": "matplotlib",
    "sklearn": "scikit-learn",
    "requests": "requests",
    "bs4": "beautifulsoup4",
    "pyspark": "pyspark",
}

# ============================================================
# EXPECTED DATASETS
# ============================================================
GB = 1024**3

# Path -> minimum size in bytes. The minimums are about 90% of the full size, so a copy
# that stopped part-way is caught. Update them if the files on the USB drive change.
EXPECTED_DATA = {
    DIR_CDRS: 11.0 * GB,
    FILE_CELL_LOCS: 20 * 1024,
    FILE_ACTIVITY_LOG: 7.5 * GB,
    FILE_HH_DATA: 2.8 * GB,
}
# ============================================================
# HELPERS FOR RECORDING AND PRINTING RESULTS
# ============================================================
results = {}


def report(name, ok, detail="", fix="", link=""):
    """Record a check and print one line (plus a fix line if it failed)."""
    results[name] = ok
    if ok:
        print(f"✅ {name}" + (f": {detail}" if detail else ""))
    else:
        print(f"❌ {name}" + (f": {detail}" if detail else ""))
        if fix:
            print(f"   Fix: {fix}")
        if link:
            print(f"   See: {link}")


def info(name, detail):
    """Print a line that is useful to know but is not a pass/fail check."""
    print(f"ℹ️  {name}: {detail}")


def clean_path(path):
    """Return the path as text, without the \\\\?\\ prefix that Windows sometimes adds."""
    return str(path).removeprefix("\\\\?\\")


def spark_fix(text):
    """Fix text for Java, Spark and Hadoop problems: on Windows, always Step 5."""
    return WINDOWS_FIX if IS_WINDOWS else text

1. Python and the course environment

Checks the Python version and that this notebook runs in the bda environment.

# ============================================================
# PYTHON VERSION
# ============================================================
version = platform.python_version()
report(
    "Python version",
    sys.version_info >= MIN_PYTHON,
    detail=f"Python {version}",
    fix=RUN_IN_BROWSER,
    link=BROWSER,
)

# ============================================================
# COURSE ENVIRONMENT
# ============================================================
env_dir = clean_path(sys.prefix)
env_name = Path(env_dir).name
report(
    "Course environment",
    env_name == ENV_NAME,
    detail=f"running from {env_dir}",
    fix="This notebook isn't using the bda environment. " + RUN_IN_BROWSER,
    link=BROWSER,
)

# ============================================================
# EDITOR (FOR INFORMATION ONLY, NOT A PASS/FAIL CHECK)
# ============================================================
if any(key.startswith("VSCODE") for key in os.environ):
    info("Editor", "running in VS Code")
else:
    info("Editor", "not running in VS Code (fine if you use JupyterLab; the course uses VS Code)")

2. Course packages

Imports each package the course notebooks use.

# ============================================================
# IMPORT EACH COURSE PACKAGE
# ============================================================
for module, label in PACKAGES.items():
    try:
        mod = importlib.import_module(module)
        report(f"Package {label}", True, detail=getattr(mod, "__version__", "installed"))
    except Exception as err:
        report(
            f"Package {label}",
            False,
            detail=f"cannot import {module} ({type(err).__name__})",
            fix=RUN_IN_BROWSER + " If it still fails, recreate the environment with "
                "`conda env create -f environment.yml`.",
            link=SETUP_ENV,
        )

3. Java

Spark runs on Java. PySpark 4 needs Java 17 or later, and JAVA_HOME must point to it.

# ============================================================
# JAVA VERSION
# ============================================================
# Look in JAVA_HOME first, then on PATH (conda's Java on macOS/Linux is not on PATH)
java_ok = False
java_home = clean_path(os.environ.get("JAVA_HOME", ""))
java_exe = None
if java_home:
    candidate = Path(java_home) / "bin" / ("java.exe" if IS_WINDOWS else "java")
    if candidate.is_file():
        java_exe = str(candidate)
if java_exe is None and shutil.which("java"):
    java_exe = clean_path(shutil.which("java"))
if java_exe is None:
    report(
        "Java",
        False,
        detail="`java` not found",
        fix=spark_fix(RUN_IN_BROWSER),
        link=WINDOWS_SPARK if IS_WINDOWS else BROWSER,
    )
else:
    # `java -version` prints to stderr, e.g. openjdk version "17.0.11" or java version "1.8.0_401"
    proc = subprocess.run([java_exe, "-version"], capture_output=True, text=True)
    text = proc.stderr + proc.stdout
    match = re.search(r'version "(\d+)(?:\.(\d+))?', text)
    if match:
        major = int(match.group(1))
        if major == 1 and match.group(2):  # old scheme: 1.8 means Java 8
            major = int(match.group(2))
        java_ok = major >= MIN_JAVA
        report(
            "Java version",
            java_ok,
            detail=f"Java {major} ({java_exe})",
            fix=spark_fix("PySpark 4 needs Java 17 or later. Use the Java in the bda environment "
                          "and make sure JAVA_HOME points to it."),
            link=SPARK_HELP,
        )
    else:
        report(
            "Java version",
            False,
            detail="could not read the version from `java -version`",
            fix=spark_fix("Run `java -version` in your terminal and compare with the troubleshooting table."),
            link=SPARK_HELP,
        )

# ============================================================
# JAVA_HOME
# ============================================================
report(
    "JAVA_HOME",
    bool(java_home) and Path(java_home).is_dir(),
    detail=java_home or "not set",
    fix=spark_fix(RUN_IN_BROWSER + " conda sets JAVA_HOME when the environment is active."),
    link=WINDOWS_SPARK if IS_WINDOWS else BROWSER,
)

4. Spark

Starts a local Spark session, creates a small DataFrame, writes it to Parquet, reads it back, and stops Spark.

⚠️ Watch out: on Windows, the Parquet step needs two extra Hadoop files. If it fails, the fix below links to the instructions.

# ============================================================
# HADOOP HELPER FILES (WINDOWS ONLY)
# ============================================================
if IS_WINDOWS:
    hadoop_home = clean_path(os.environ.get("HADOOP_HOME", ""))
    report(
        "HADOOP_HOME",
        bool(hadoop_home),
        detail=hadoop_home or "not set",
        fix=WINDOWS_FIX,
        link=WINDOWS_SPARK,
    )
    if hadoop_home:
        hadoop_bin = Path(hadoop_home) / "bin"
        missing = [f for f in ("winutils.exe", "hadoop.dll") if not (hadoop_bin / f).is_file()]
        report(
            "Hadoop helper files",
            not missing,
            detail=f"missing from {hadoop_bin}: {', '.join(missing)}" if missing else str(hadoop_bin),
            fix=WINDOWS_FIX,
            link=WINDOWS_SPARK,
        )
# ============================================================
# START SPARK, BUILD A DATAFRAME, WRITE AND READ PARQUET
# ============================================================
if not results.get("Package pyspark"):
    report("Spark", False, detail="skipped because PySpark is not installed",
           fix="Fix the PySpark package check above first.", link=WINDOWS_SPARK if IS_WINDOWS else SETUP_ENV)
elif not java_ok:
    report("Spark", False, detail="skipped because Java is missing or too old",
           fix=spark_fix("Fix the Java check above first."), link=SPARK_HELP)
else:
    from pyspark.sql import SparkSession

    spark = None
    stage = "starting a Spark session"
    try:
        spark = (
            SparkSession.builder
            .master("local[*]")
            .appName("bda-check-setup")
            .getOrCreate()
        )
        report("Spark session", True, detail=f"Spark {spark.version}")

        stage = "creating a DataFrame"
        df = spark.createDataFrame(
            [("Kigali", 1_745_555), ("Lilongwe", 1_122_000), ("Nairobi", 4_397_073)],
            ["city", "population"],
        )
        report("Spark DataFrame", df.count() == 3, detail=f"{df.count()} rows")

        stage = "writing and reading Parquet"
        with tempfile.TemporaryDirectory() as tmp:
            out = str(Path(tmp) / "check.parquet")
            df.write.mode("overwrite").parquet(out)
            n = spark.read.parquet(out).count()
        report("Spark Parquet write/read", n == 3, detail=f"{n} rows read back")
    except Exception as err:
        first_line = str(err).strip().splitlines()[0][:150] if str(err).strip() else type(err).__name__
        report(
            "Spark",
            False,
            detail=f"failed while {stage}: {first_line}",
            fix=spark_fix("Look up this error in the troubleshooting table."),
            link=SPARK_HELP,
        )
    finally:
        if spark is not None:
            spark.stop()

5. Datasets

Checks that the files from the USB drive are in data/raw/ and were copied completely.

# ============================================================
# CHECK EACH DATASET IS THERE AND FULLY COPIED
# ============================================================
if not (DIR_COURSE / "environment.yml").exists():
    report(
        "Datasets",
        False,
        detail=f"{DIR_COURSE} doesn't look like the course folder (no environment.yml)",
        fix="Open the course folder in VS Code (File → Open Folder), then open this notebook from it.",
        link=DATASETS,
    )
else:
    for path, min_size in EXPECTED_DATA.items():
        label = f"Dataset {path.name}"
        if not path.exists():
            fix = "Copy everything from the datasets-abidjan-2026 folder on the USB drive into data/raw/."
            if path == FILE_CELL_LOCS and (DIR_DATA / "sythetic-cell-locs.csv").exists():
                fix = "The file is there with a typo in its name: rename sythetic-cell-locs.csv to synthetic-cell-locs.csv."
            report(label, False, detail=f"not found in {DIR_DATA}", fix=fix, link=DATASETS)
            continue
        if path.is_dir():
            files = list(path.glob("*.csv"))
            size = sum(f.stat().st_size for f in files)
            detail = f"{len(files):,} CSV files, {size / GB:.1f} GB"
        else:
            size = path.stat().st_size
            detail = f"{size / GB:.2f} GB" if size >= 0.1 * GB else f"{size / 1024:.0f} KB"
        report(
            label,
            size >= min_size,
            detail=detail,
            fix=f"The copy looks incomplete. Delete it and copy {path.name} from the USB drive again.",
            link=DATASETS,
        )
    free_gb = shutil.disk_usage(DIR_COURSE).free / GB
    info("Free disk space", f"{free_gb:.0f} GB left on the drive with the course folder")

6. Are you ready?

# ============================================================
# SUMMARY OF THE CHECKS
# ============================================================
failed = [name for name, ok in results.items() if not ok]
software_failed = [name for name in failed if not name.startswith("Dataset")]
data_failed = [name for name in failed if name.startswith("Dataset")]

print()
if not failed:
    print("🎉 You're ready for the course! Every check passed.")
else:
    if software_failed:
        print(f"❌ Software: {len(software_failed)} check(s) failed:")
        for name in software_failed:
            print(f"   - {name}")
    else:
        print("✅ Software: Python, the bda environment, Java and Spark are ready.")
    if data_failed:
        print(f"❌ Data: {len(data_failed)} dataset check(s) failed:")
        for name in data_failed:
            print(f"   - {name}")
    print()
    print("Fix the first one (its fix is printed above), then run this notebook again: Run All.")
    print(f"Still stuck? See {TROUBLESHOOT}, or ask at the setup clinic.")

7. See Spark in action

Now that everything works, start Spark, build a small table, and look at Spark’s web interface. Run the next cell and, while it runs, open http://localhost:4040 in your browser to see the Spark UI (jobs, stages and executors).

💡 Tip: the cell stops Spark at the end, which also closes the UI. To keep the UI open longer, put a # in front of spark.stop(), and run spark.stop() in a new cell when you’re done.

# ============================================================
# START A LOCAL SPARK SESSION
# ============================================================
from pyspark.sql import SparkSession
import pyspark.sql.functions as F

spark = (
    SparkSession.builder
    .master("local[*]")
    .appName("bda-see-spark")
    .getOrCreate()
)
# The UI is usually on port 4040 (4041 if another Spark session is running)
ui_port = spark.sparkContext.uiWebUrl.rsplit(":", 1)[1]
print(f"Spark UI: http://localhost:{ui_port}")

# ============================================================
# BUILD A SMALL TABLE AND ADD A COLUMN
# ============================================================
# Approximate city populations, rounded, for illustration only
cities = spark.createDataFrame(
    [("Abidjan", 6_300_000), ("Dakar", 4_000_000), ("Accra", 2_600_000)],
    ["city", "population"],
)
cities.withColumn("pop_millions", F.round(F.col("population") / 1e6, 2)).show()

# ============================================================
# STOP SPARK (THIS ALSO CLOSES THE SPARK UI)
# ============================================================
spark.stop()

Summary

  • The course runs in one conda environment, bda, which includes Python, Java 17 and PySpark.
  • When this notebook shows ✅ for every check, your laptop is ready for the hands-on sessions.
  • If a check fails, fix the first ❌ using its printed fix, then click Run All again.

Next: the Python foundations notebooks for Module 0.