DS 208 · Week 12

Integrative Project & Presentations

One dataset and the whole toolkit: loading, cleaning, analysing and visualising it, then presenting the findings to the class.

Programming for Data Science · University of the Philippines Cebu

Outline

All course skills in one project

Key terms

Ten terms for the project

pipeline

The fixed order of steps that turns raw data into an answer: load, clean, analyse, visualise, communicate.

e.g. one script that runs all five, top to bottom

research question

The one specific thing a project sets out to find, written as a question the data can answer.

e.g. "Which region's flood-control projects take longest to finish?"

deliverable

An item that must be submitted. Here: the project repository and the talk.

e.g. a repo with a README, code, tests and pinned requirements

rubric

The marking guide: the criteria on which a project is judged, and what earns full marks for each.

e.g. "It runs: fresh clone, no edits needed"

README

A short text file at the top of the project saying what it is, how to run it, and where the data comes from.

e.g. README.md (week 11)

module

A .py file of functions that other code can import (week 4).

e.g. src/clean.py, used as from src.clean import coerce_types

test

A small function that runs code on known input and automatically asserts that the result is correct.

e.g. def test_coerce_counts_failures(): run by pytest

fixture

A small, hand-made dataset that a test runs on, with one row for each relevant case.

e.g. five rows: normal, unfinished, no budget, impossible, unparseable

invariant

A fact that must stay true if a step worked (week 11).

e.g. "a merge does not change the row count"

limitation

Something the data or method cannot show, stated openly next to the finding.

e.g. "the place-name pattern matched only 36% of descriptions"

Previous sessions

Eleven weeks combined into one workflow

Python, NumPy, pandas, charts, data sources, text, and reproducibility. Individually, each is a technique. Combined, they form a pipeline that answers a question.

Parts

Every step has been covered in isolation.

Whole

The project connects them.

A pipeline is, by analogy, a kitchen routine: shop (load), wash and chop (clean), cook (analyse), plate (visualise), serve (communicate); the project prepares one whole meal.

Part A

The pipeline

From raw data to a finding.

Each stage has been used on its own (weeks 5–11). This part arranges them in one order, starting from a question instead of a dataset.

Conceptual model

Five stages of a data project

Load Clean Analyse Visualise Communicate most of the effort lives in Clean — expect that
Prerequisites

Pipeline stages and the weeks that cover them

StageFrom weekTools
Load9read_csv, SQL, APIs
Clean3, 4, 10files, errors, strings + regex
Analyse5, 6, 7NumPy, pandas, groupby, merge
Visualise8matplotlib, seaborn
Communicate11, 12reproducible repo + this talk
Research question

A project begins with a question

A project starts from a question such as "does city size predict income?", not from a dataset. A clear research question (the one thing a project sets out to find) determines what to load, what to clean, and what counts as an answer.

A good one is specific (names what, where, when), answerable with the available columns, and small enough for the available time.

Weak start

"I'll explore this CSV and see what's there."

Strong start

"Which region grew fastest from 2015 to 2024, and why?"

Part B

Structuring the project

Reproducible, documented, transparent.

Part A covered the stages. This part packages them so that another person can run the project, read it, and trust it.

Project setup

Four requirements of every project

Runnable code

The project’s functions and tests run here

The cleaning functions and their tests on the next slides run in the browser: the same code that will sit in src/clean.py and tests/. Commands typed in a terminal (python -m src.pipeline, pytest) have no Run button.

A small test table

The tests use a five-row table built to contain one example of each problem the course found in the flood data.

import io, sys print("pandas version:", pd.__version__) print("64-bit Python:", sys.maxsize > 2**32) t = pd.read_csv(io.StringIO("city,pop\nCebu,964000")) print(t.dtypes) pandas version: 3.0.5 64-bit Python: True city str pop int64 dtype: object
  • pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browser
  • t.dtypeseach column’s type: str on the laptop, object in the browser
Entry point

Running a pipeline without clicking cells

A notebook needs a person. A script (a .py file run from the terminal) does not, so it can be scheduled, tested in CI (automatic checks on every push, week 11), and re-run by someone who has never seen it. Its entry point is the function that starts everything, here main().

The __main__ guard

Lets the same file be imported by tests and run from the command line. Without it, importing runs the whole pipeline.

# src/pipeline.py def main(): df = load_raw(RAW_PATH) df = coerce_types(df) df = add_duration(df) df, dropped = drop_unusable(df, ["budget"]) log.info("dropped %s rows", dropped) df.to_parquet(PROCESSED_PATH) return df if __name__ == "__main__": main() $ python -m src.pipeline
  • def main():the whole pipeline as one function: each line is one stage, written as a function in src/
  • df.to_parquet(PROCESSED_PATH)save the cleaned table; Parquet is a compact file format for tables
  • if __name__ == "__main__":true only when this file is run directly, not when another file imports it; so main() runs only on purpose
  • $ python -m src.pipelinetyped in a terminal (the $ is the prompt and is not typed): run src/pipeline.py as a module
Explicit failure

Early failure is preferable to a wrong result

Code that can legitimately fail is wrapped in try/except. Genuine bugs are allowed to crash, because a bare except converts a bug into a wrong number.

Catch narrowly, assert widely

The predicted exception is handled and the expected invariants are asserted. Anything else should stop the run.

# fails on purpose: read the last line path = "data/flood_raw.csv" # not there yet on a fresh clone try: df = pd.read_csv(path) except FileNotFoundError: raise SystemExit(f"missing {path}: see README") assert len(df) > 0, "loaded an empty file" assert "budget" in df.columns, "schema changed" missing data/flood_raw.csv: see README
  • raise SystemExit(f"missing {path}: …")stop at once with a message that says what to do, instead of a long traceback
  • assert "budget" in df.columns, …check the shape of the data before any analysis uses it
  • except: passnever: a swallowed error is how a wrong answer ships
The README

Three sections, written on day one

Code and narrative

A notebook that reads top to bottom

Markdown between the code cells explains the why: the question, each choice, and what a result means. A reader should follow without running anything. (A markdown cell is a notebook cell of formatted text, not code.)

Code only

A reader has to reconstruct the author’s intent.

Code + narrative

Each step is introduced, justified, and interpreted.

Project versus notebook

A project is a notebook plus its supporting files

The analysis is the same; the difference is whether another person can run it.

Directory layout

A layout that newcomers can navigate

Each directory answers a question a reader will have. The structure serves as documentation.

raw/ is read-only, always

An incorrect cleaning step can be rerun. A hand-edited raw file cannot be recovered.

flood_project/ data/ raw/ # never edited processed/ # written by code src/ __init__.py load.py # reading files/APIs clean.py # one job per module analyse.py tests/ test_clean.py notebooks/ 01-explore.ipynb README.md requirements.txt
  • data/raw/, data/processed/the files as downloaded (never edited) and the files the code writes
  • src/__init__.pyan empty file that turns src/ into a package, so import src.clean works
  • tests/test_clean.pythe tests for clean.py; pytest finds files named test_…
  • notebooks/01-explore.ipynbexploring and the story; the reusable logic lives in src/
Cells become functions

Extracting repeated cells into functions

A cell that is repeatedly re-run should become a function. Extracting it (moving the code into a named function in src/) is what makes it testable.

One job per function

If the name needs an "and", it is two functions. coerce_types, not clean_and_derive_and_filter.

  • def coerce_types(df):the type conversions from week 6, written once and named
  • out = df.copy()work on a copy, so the caller’s frame never changes by surprise
  • def add_duration(df):week 6’s derived column, also named: days from start to completion
# src/clean.py def coerce_types(df): out = df.copy() # never modify the caller's frame out["budget"] = pd.to_numeric(out.budget, errors="coerce") for col in ("start_date", "completion_date"): out[col] = pd.to_datetime(out[col], errors="coerce") return out def add_duration(df): out = df.copy() out["duration"] = (out.completion_date - out.start_date).dt.days return out demo = pd.DataFrame({"budget": ["5000000"], "start_date": ["2024-01-10"], "completion_date": ["2024-06-30"]}) print(add_duration(coerce_types(demo)).dtypes) budget int64 start_date datetime64[us] completion_date datetime64[us] duration int64 dtype: object
Docstrings

Docstrings explain why; code shows what

A docstring is the text in triple quotes right under def (week 4). A docstring repeating the function name is noise. One explaining a decision is the only place that reasoning survives.

Writing for later readers

Months later, the reason errors="coerce" was deliberate will be forgotten. The docstring records it.

def drop_unusable(df, subset): """Drop rows missing any of `subset`, and report how many went. Deliberately NOT a bare df.dropna(): that removes rows for reasons unrelated to the question and silently changes which population the analysis is about. """ before = len(df) out = df.dropna(subset=subset) return out, before - len(out) demo = pd.DataFrame({"budget": [1.0, None, 3.0], "notes": [None, "x", None]}) kept, dropped = drop_unusable(demo, ["budget"]) print(len(kept), "kept,", dropped, "dropped") 2 kept, 1 dropped
  • df.dropna(subset=subset)drop a row only if one of the listed columns is missing, not any column
  • return out, before - len(out)hand back two things: the smaller table and how many rows were dropped, for reporting
Integrity

Making analytical choices visible

Testing

Tests on five rows, not 34,079

A test should fail for one reason, and be readable when it does.

Hand-built fixtures

Each row exists to exercise one case

Tests do not use the real dataset. Five rows represent every relevant case, including the broken ones found this term. That tiny hand-made table is a fixture.

Five cases from the course

Normal, unfinished, no budget, the impossible row (it ends before it starts; the flood data has one, week 11), and an unparseable value. Each is a bug this class encountered.

RAW = pd.DataFrame([ {"id": "A1", "budget": "1000000", "start_date": "2024-01-10", "completion_date": "2024-06-30"}, # normal {"id": "A2", "budget": "2500000", "start_date": "2024-02-01", "completion_date": ""}, # unfinished {"id": "A3", "budget": "", "start_date": "2024-03-05", "completion_date": "2024-09-01"}, # no budget {"id": "A4", "budget": "800000", "start_date": "2016-05-23", "completion_date": "2016-05-06"}, # impossible {"id": "A5", "budget": "n/a", "start_date": "2024-04-01", "completion_date": "2024-08-15"}, # unparseable ]).replace("", pd.NA) print(RAW) id budget start_date completion_date 0 A1 1000000 2024-01-10 2024-06-30 1 A2 2500000 2024-02-01 NaN 2 A3 NaN 2024-03-05 2024-09-01 3 A4 800000 2016-05-23 2016-05-06 4 A5 n/a 2024-04-01 2024-08-15
  • .replace("", pd.NA)make empty text a real missing value, as read_csv would
  • A2, A3, A5an unfinished project, a missing budget, and a budget that is not a number
  • A4the impossible project from week 6: completed 17 days before it started
Exercise · 3 min

Testing invariants rather than implementation

A test is a function that runs code on known input and asserts the result. It asserts the invariant, the property that must hold if the step worked. Those survive refactoring (rewriting how code works without changing what it does); assertions about internals do not.

Manual checks made executable

Row counts, impossible values, NaN counts: checks previously run by hand. A test runs them on every change, including late-night ones.

Tasks

  1. Predict whether both tests pass.
  2. Select ▶ Run / Edit and run the code.
  3. In coerce_types (on the Run / Edit copy), delete errors="coerce" and run again. What happens?

Result on the lecture laptop (select to reveal)

2 tests passed: two budgets fail to convert (A3 empty, A5 “n/a”) and exactly one project, A4, has a negative duration. Without errors="coerce", coerce_types stops with ValueError: Unable to parse string "n/a": the test catches the change before the real data does.

# coerce_types, add_duration, RAW: from the previous slides def test_coerce_counts_failures(): out = coerce_types(RAW) assert out.budget.isna().sum() == 2 # A3 empty + A5 "n/a" def test_surfaces_the_impossible_row(): out = add_duration(coerce_types(RAW)) assert (out.duration < 0).sum() == 1 assert out.loc[out.duration < 0, "id"].iloc[0] == "A4" test_coerce_counts_failures() test_surfaces_the_impossible_row() print("2 tests passed") # pytest finds and runs these itself
  • def test_…():pytest runs every function whose name starts with test_; it passes if no assert fails
  • out.budget.isna().sum() == 2exactly two budgets became NaN: the empty one (A3) and "n/a" (A5)
  • (out.duration < 0).sum() == 1exactly one row finishes before it starts, and the next line checks it is A4
  • cannot regressto regress is for a fixed bug to come back; this test would catch it if it did
Under eight seconds

Automatic tests on every change

$ pytest tests/ -q ..... [100%] 5 passed in 7.83s
What to test

Three categories worth testing

The aim is not coverage (in testing, the share of code lines that some test runs), but encoding the mistakes that are costly when they recur.

pandas itself is not tested

The library is assumed to work. Tests cover the project’s logic: the decisions made about this data.

TEST: shape invariants "a merge must not change row count" domain rules "duration cannot be negative" the bugs you already hit "unparseable budget -> NaN, not a crash" DO NOT TEST: that pandas can add numbers exact float equality (use approx) plotting output
  • shape invariantsfacts about rows and columns: counts that must not change
  • domain rulesfacts about the real world the data describes: a project cannot end before it starts
  • use approx0.1 + 0.2 is not exactly 0.3 in a computer; pytest.approx allows a tiny difference
Review question

Question (select to reveal the answer)

In the pipeline, which stage usually takes the most time?

A · Load
B · Clean
C · Visualise
D · Communicate

B — Clean.

Real data contains missing values, wrong types, and stray text. Cleaning routinely dominates a project, so time is allocated for it and the steps are documented.

Break

  Five minutes

Next: turning the project into a talk.

Part C

Presenting

Presenting findings and defending them.

Part B produced a project that runs and can be trusted. This part covers explaining it to an audience in a few minutes and answering questions honestly.

Leading with the finding

One talk, one message

The single sentence the audience should remember is decided first, and every slide builds toward it. Everything else is support.

That sentence is the finding: the answer to the research question, in plain words, with a number where possible.

Weak

"Here is everything I did, in order."

Strong

"Visayan cities grew fastest; the evidence follows."

Talk structure

Five parts of a talk, in order

BeatContent
QuestionWhat the project set out to learn
DataIts source and its quality
MethodThe steps applied to it
FindingThe answer: the one message
LimitationWhere it should not be trusted
Slide design

Slides support the speaker; they are not the report

Delivery

Presenting the findings rather than the code

A line-by-line tour is not useful. The talk explains the question, the finding, and its meaning. One rehearsal aloud reveals weak transitions.

Do

Focus on the finding; let the charts carry the argument.

Don't

Read the slides aloud, or walk through every cell.

Eleven weeks, one pipeline

Course tools by pipeline stage

StageWeekTools
Get it9read_csv / read_sql / requests — and cache it
Shape it6–7dtypes, loc, groupby, merge, transform
Compute it5NumPy: vectorise, mask, axis — never a loop
Parse the text10.str, regex — then report coverage
Show it8subplots, labels, bars from zero, saved with bbox_inches
Ship it11git, pinned requirements, tests, README
Presenting code

Presenting decisions rather than syntax

A for loop on a projector is not informative. The talk shows the one function that contains a judgement call, and explains it. (Boilerplate is the routine code every project repeats, like imports and axis labels.)

Results first, code on request

The output comes first. The notebook stays open in another tab in case of questions about the code.

DO show: the function with the decision in it (5-10 lines, with its docstring) the test that encodes an invariant ("a merge must not change row count") the output, large enough to read DON'T show: imports boilerplate plotting calls anything you would scroll
Deliverables

Deliverables: a repository and a talk

1 · The repository (the code, on Git)

  • README.md: the question, how to run it, where the data comes from
  • requirements.txt with pinned versions
  • src/: the cleaning and analysis as functions with docstrings
  • notebooks/: the story, text between the code, runs top to bottom
  • tests/: at least one shape invariant, one domain rule, one bug encountered
  • data/raw/ untouched; data and secrets not committed

2 · The talk (to the class)

  • Five beats: question, data, method, finding, limitation
  • One message the audience can repeat afterwards
  • Labelled charts, not tables of numbers or scrolling code
  • One function that holds a decision, shown and explained
  • Q&A: weak spots named before they are raised
Marking

Running on another machine is weighted highest

CriterionWhat earns full marks
It runsFresh clone, fresh environment, pinned requirements, Restart & Run All — no edits needed
StructureLogic in src/, notebooks for exploring; raw data never modified
CorrectnessTests exist and pass; invariants asserted at the steps that can silently break
ReadabilityFunctions do one job; docstrings say why; names mean something
HonestyCoverage and row counts reported; no bare excepts; limits stated
The rubric: interpretation

Each criterion as a self-check

CriterionMeaningSelf-check
It runsAnother person can run it and obtain the same numbersClone to a new folder, new environment, pip install -r requirements.txt, Restart & Run All
StructureReusable code lives in files of functions, not in notebook cellsThe notebook can import the cleaning from src/; data/raw/ is as downloaded
CorrectnessThe steps that could fail silently are verifiedpytest -q shows only dots; an assert after each merge and cleaning step
ReadabilityA newcomer can follow itEvery function name says its one job; docstrings say why; no df2, x
HonestyDropped data and unsupported claims are statedRows before/after cleaning reported; regex coverage reported; limitations in the README and talk
Names as documentation

Descriptive names: the cheapest readability improvement

Code is read far more often than it is written, and mostly when something is wrong and time is short.

df is fine. df2 is not.

With one frame in scope, df is acceptable. With two, both need real names: projects and regions.

# meaningless df2 = df[df.b > 1e8] x = df2.groupby("r").mean() # says what it holds large = projects[projects.budget > 1e8] by_region = large.groupby("region").budget.mean() # and the unit, when there is one duration_days = ... budget_php = ...
  • 1e8scientific notation for 100,000,000 (a 1 followed by 8 zeros): here, budgets over ₱100 million
  • df.b, "r"one-letter names force the reader to look up what they hold
  • by_region = …the name says what is inside: the average budget of large projects, per region
Self-review

Six checks before submission

Further study

Topics that build on this toolkit

Each topic below assumes the ability to load, shape, compute and ship data reliably, which is what this eleven-week course developed.

Depth before breadth

SQL and testing pay off immediately and in every job. New libraries are easy once the habits are in place.

None of these is needed for the project. They are topics for later study: polars and duckdb are faster table tools, scikit-learn is for machine learning, Flask/FastAPI build web APIs, streamlit turns a script into a web dashboard. Window functions and CTEs are more advanced SQL; parametrize runs one test on many inputs.

immediately useful: SQL beyond SELECT — window functions, CTEs pytest properly — fixtures, parametrize polars / duckdb when pandas stops fitting in memory builds directly on this: scikit-learn (CMSC 173) APIs you write, not just call (Flask/FastAPI) dashboards (streamlit) the habit that carries: extract, test, pin, document
Main lesson

Working code that another person can run

Exercise · 8 min

Refactoring a notebook into a project

1 · Extract two functions

Select the two most frequently re-run cells. Move them into src/clean.py with docstrings that say why.

2 · Write the fixture

Five hand-written rows covering: normal, missing, and one broken case encountered this term.

3 · Write three tests

One shape invariant, one domain rule, one for the bug. Run pytest -q in a terminal, from the project folder.

4 · Break it on purpose

Change a function so a test fails. Read the failure output, which is what a real failure will look like.

Review question

Question (select to reveal the answer)

A clean() function works in the notebook. What is the first thing to do before relying on it?

A · Optimise it — it is called on 34,079 rows
B · Move it into a module and write a test on a handful of hand-made rows
C · Add a try/except so it never crashes
D · Run it on the full dataset again to be sure
B. A notebook cell cannot be tested, imported or reviewed. Extracting it makes all three possible, and a five-row fixture catches the cases the real data may not contain today. C is actively harmful — a bare except turns a bug into a wrong number. D confirms nothing: it already ran, which is the only reason it appears to work.
Review question

Question (select to reveal the answer)

Which of these is worth writing a test for?

A · That pd.to_numeric converts "123" to 123
B · That the project’s merge does not change the row count
C · That matplotlib produces a PNG
D · That two floats are exactly equal
B. It is the project’s invariant: a duplicated join key silently doubling rows is a bug this course met in week 7, and the test catches it on every change. A tests pandas, which can be assumed to work. C tests a library. D is actively bad practice: floating point makes exact equality unreliable, so pytest.approx is used.
Questions and answers

Acknowledging uncertainty in Q&A

The presenter knows the project's weak spots best and names them first. When a question goes beyond what was tested, this is stated plainly; guessing loses trust.

Preparation

The three least welcome questions are listed and answered in advance.

Honesty

"That is outside what I tested" is preferable to a confident wrong answer.

Review question

Question (select to reveal the answer)

What should be decided first when building a presentation?

A · the colour theme
B · the single message
C · how many slides
D · the font

B — the single message.

The one sentence the audience should leave with is decided first, and every slide builds toward it. Design choices come after the message, never before.

Before submission

Four-point check

CheckCriterion
ReproducibleAnother person can clone it and rerun it cleanly
DocumentedThe README + notebook explain the why
HonestCleaning choices and limitations are stated
ClearOne message is clear to a newcomer
Summary

Load, clean, analyse, show, share

Glossary

This week's terms, one line each

Key terms

pipeline
load → clean → analyse → visualise → communicate, in order
research question
the one specific, answerable thing the project sets out to find
deliverable
what is submitted: the repository and the talk
rubric
the marking guide: criteria and what earns full marks
README
text file saying what the project is, how to run it, where data comes from
module
a .py file of functions that can be imported with import
test
a function that runs code on known input and asserts the result
fixture
a tiny hand-made dataset a test runs on
invariant
a fact that must stay true if a step worked
limitation
what the data or method cannot show, stated openly

Additional terms

finding
the answer to the research question, in one plain sentence
criterion
one thing the rubric judges (plural: criteria)
script / entry point
a .py file run from the terminal / its starting function, main()
__main__ guard
if __name__ == "__main__": runs only when the file is run directly
bare except
except: with no error named; hides real bugs
docstring
text in triple quotes under def; says why
refactor
restructure code without changing what it does
fresh clone
a new copy of the repo on a machine that has never seen it
cherry-pick
showing only the results that support a preferred conclusion
boilerplate
routine code every project repeats
Next steps

Foundations for further study

Conclusion

End of the course

The course has covered loading, cleaning, analysing, visualising, and presenting real data, starting from little or no programming background.

DS 208 · Programming for Data Science · University of the Philippines Cebu