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
The full sequence from raw data to a finding, each stage a skill already covered.
A project that is reproducible, documented, and transparent.
Presenting the findings clearly and defending them in Q&A.
This session introduces no new syntax. It combines eleven weeks of material into a project that can be presented and defended.
A clear plan for the project and the talk that presents it.
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
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?"
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
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"
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)
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
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
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
A fact that must stay true if a step worked (week 11).
e.g. "a merge does not change the row count"
Something the data or method cannot show, stated openly next to the finding.
e.g. "the place-name pattern matched only 36% of descriptions"
Python, NumPy, pandas, charts, data sources, text, and reproducibility. Individually, each is a technique. Combined, they form a pipeline that answers a question.
Every step has been covered in isolation.
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.
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.
The process is rarely linear: analysis often reveals problems that require further cleaning. The overall structure is the same for every project.
pd.read_csv)groupby, mergeCleaning routinely takes the most time. This is normal, not a failure.
| Stage | From week | Tools |
|---|---|---|
| Load | 9 | read_csv, SQL, APIs |
| Clean | 3, 4, 10 | files, errors, strings + regex |
| Analyse | 5, 6, 7 | NumPy, pandas, groupby, merge |
| Visualise | 8 | matplotlib, seaborn |
| Communicate | 11, 12 | reproducible repo + this talk |
Nothing here is new. The project is assembly rather than new learning: it combines tools already used.
For difficulty with a stage, that week's lab contains the relevant pattern.
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.
"I'll explore this CSV and see what's there."
"Which region grew fastest from 2015 to 2024, and why?"
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.
From the first commit, so nothing is ever lost.
A requirements.txt so it runs on any machine.
What the project asks, and how to run it.
A clear layout — data/ (the data files), src/ (short
for "source": the modules, .py files of functions),
notebooks/ — allows a newcomer, or the author later, to navigate the project in minutes.
A project is complete only when another person can clone it and reproduce the result.
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.
The tests use a five-row table built to contain one example of each problem the course found in the flood data.
pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browsert.dtypeseach column’s type: str on the laptop, object in the browserA 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().
Lets the same file be imported by tests and run from the command line. Without it, importing runs the whole 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 tablesif __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 moduleCode 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.
The predicted exception is handled and the expected invariants are asserted. Anything else should stop the run.
raise SystemExit(f"missing {path}: …")stop at once with a message that says what to do, instead of a long tracebackassert "budget" in df.columns, …check the shape of the data before any analysis uses itexcept: passnever: a swallowed error is how a wrong answer shipsTwo sentences stating the question it answers and the data it uses.
The exact commands, in order, starting from a fresh clone. They are tested on another machine.
Source, licence, date accessed — and how to obtain it, since data/ is gitignored.
The README (README.md, a text file at the top of the repo) is the first thing a marker opens. It is written first, while the author still knows what is and is not obvious. By the end of a project, the author has forgotten what was confusing on the first day.
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.)
A reader has to reconstruct the author’s intent.
Each step is introduced, justified, and interpreted.
The analysis is the same; the difference is whether another person can run it.
Each directory answers a question a reader will have. The structure serves as documentation.
An incorrect cleaning step can be rerun. A hand-edited raw file cannot be recovered.
data/raw/, data/processed/the files as downloaded (never edited) and the files the code writessrc/__init__.pyan empty file that turns src/ into a package, so import src.clean workstests/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/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.
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 namedout = df.copy()work on a copy, so the caller’s frame never changes by surprisedef add_duration(df):week 6’s derived column, also named: days from start to completionA 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.
Months later, the reason errors="coerce" was deliberate will be forgotten. The docstring records it.
df.dropna(subset=subset)drop a row only if one of the listed columns is missing, not any columnreturn out, before - len(out)hand back two things: the smaller table and how many rows were dropped, for reportingEvery dropped row is a decision; the report states which rows and why.
Small samples and missing data are stated before others point them out. A limitation is something the data or method cannot show.
The result found is reported, not the one wanted. (To cherry-pick is to show only the results that support a preferred conclusion.)
A recurring principle from DS 227 (the companion course): every default is a choice. Making choices visible makes the work trustworthy.
An honest, modest result is preferable to an impressive, unrepeatable one.
A test should fail for one reason, and be readable when it does.
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.
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.
.replace("", pd.NA)make empty text a real missing value, as read_csv wouldA2, A3, A5an unfinished project, a missing budget, and a budget that is not a numberA4the impossible project from week 6: completed 17 days before it startedA 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.
Row counts, impossible values, NaN counts: checks previously run by hand. A test runs them on every change, including late-night ones.
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.
def test_…():pytest runs every function whose name starts with test_; it passes if no assert failsout.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 A4cannot regressto regress is for a fixed bug to come back; this test would catch it if it didReading it: pytest tests/ -q runs every test in tests/ quietly; each . is one test that passed (a failure shows F); 5 passed in 7.83s is the summary. The five dots show the benefit: checks previously run by hand all term now run automatically, and a change that breaks one is reported immediately rather than in a chart three weeks later.
Tests also run before any submission. A test failing the night before is useful; the same bug found by the marker is costly.
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.
The library is assumed to work. Tests cover the project’s logic: the decisions made about this data.
shape invariantsfacts about rows and columns: counts that must not changedomain rulesfacts about the real world the data describes: a project cannot end before it startsuse approx0.1 + 0.2 is not exactly 0.3 in a computer; pytest.approx allows a tiny differenceIn the pipeline, which stage usually takes the most time?
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.
Cleaning is usually the longest stage, and plans should account for it.
Most of the work is getting the data clean.
Next: turning the project into a talk.
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.
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.
"Here is everything I did, in order."
"Visayan cities grew fastest; the evidence follows."
| Beat | Content |
|---|---|
| Question | What the project set out to learn |
| Data | Its source and its quality |
| Method | The steps applied to it |
| Finding | The answer: the one message |
| Limitation | Where it should not be trusted |
This structure fits five minutes or fifty. Each beat takes one or two slides at most.
A slide that does not serve one of these beats is removed.
A slide makes a single point; a slide with two is split.
A chart is legible from the back row; a grid of numbers is not.
Title, axes, units, and honest baselines, as in Week 8.
This deck follows the same principles: little text, one concept, and a visual that carries the point.
Readable from the back, understood in five seconds.
A line-by-line tour is not useful. The talk explains the question, the finding, and its meaning. One rehearsal aloud reveals weak transitions.
Focus on the finding; let the charts carry the argument.
Read the slides aloud, or walk through every cell.
| Stage | Week | Tools |
|---|---|---|
| Get it | 9 | read_csv / read_sql / requests — and cache it |
| Shape it | 6–7 | dtypes, loc, groupby, merge, transform |
| Compute it | 5 | NumPy: vectorise, mask, axis — never a loop |
| Parse the text | 10 | .str, regex — then report coverage |
| Show it | 8 | subplots, labels, bars from zero, saved with bbox_inches |
| Ship it | 11 | git, pinned requirements, tests, README |
Six stages: the same five-stage pipeline, with Clean split into "shape it", "compute it" and "parse the text", and Communicate called "ship it". Each has been practised separately. The project is the first time they form one artifact, and the ordering is not arbitrary: each stage assumes the one above it was done properly.
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.)
The output comes first. The notebook stays open in another tab in case of questions about the code.
README.md: the question, how to run it, where the data comes fromrequirements.txt with pinned versionssrc/: the cleaning and analysis as functions with docstringsnotebooks/: the story, text between the code, runs top to bottomtests/: at least one shape invariant, one domain rule, one bug encountereddata/raw/ untouched; data and secrets not committedA deliverable is an item that must be submitted. Everything on this slide was covered today; the next two slides say how it is marked. The course page lists the due date, talk length and submission location.
A classmate clones the repo, installs requirements.txt in a fresh environment, runs it top to bottom and obtains the same numbers, with no edits.
| Criterion | What earns full marks |
|---|---|
| It runs | Fresh clone, fresh environment, pinned requirements, Restart & Run All — no edits needed |
| Structure | Logic in src/, notebooks for exploring; raw data never modified |
| Correctness | Tests exist and pass; invariants asserted at the steps that can silently break |
| Readability | Functions do one job; docstrings say why; names mean something |
| Honesty | Coverage and row counts reported; no bare excepts; limits stated |
"It runs" is first because everything else is unverifiable without it. A brilliant analysis nobody can execute scores below a modest one that works on the first try.
| Criterion | Meaning | Self-check |
|---|---|---|
| It runs | Another person can run it and obtain the same numbers | Clone to a new folder, new environment, pip install -r requirements.txt, Restart & Run All |
| Structure | Reusable code lives in files of functions, not in notebook cells | The notebook can import the cleaning from src/; data/raw/ is as downloaded |
| Correctness | The steps that could fail silently are verified | pytest -q shows only dots; an assert after each merge and cleaning step |
| Readability | A newcomer can follow it | Every function name says its one job; docstrings say why; no df2, x |
| Honesty | Dropped data and unsupported claims are stated | Rows before/after cleaning reported; regex coverage reported; limitations in the README and talk |
If the right-hand column holds for every row, the score is predictable before submission. The Exercise activity and the lab both practise these checks.
Code is read far more often than it is written, and mostly when something is wrong and time is short.
With one frame in scope, df is acceptable. With two, both need real names: projects and regions.
1e8scientific notation for 100,000,000 (a 1 followed by 8 zeros): here, budgets over ₱100 milliondf.b, "r"one-letter names force the reader to look up what they holdby_region = …the name says what is inside: the average budget of large projects, per regionA name that needs "and" indicates two functions. If it is longer than a screen, it is doing several things.
Paths relative, README says where the file comes from, data/raw/ untouched.
Bare except, an extraction with unreported coverage, a merge with no row-count check.
The remaining three checks: the requirements are pinned, the tests pass, and it runs from a fresh clone. The review takes about twenty minutes. Every one of these has cost this course real time in a previous week.
Each topic below assumes the ability to load, shape, compute and ship data reliably, which is what this eleven-week course developed.
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.
pandas 3 changed the copy rules during this course. Such changes will recur.
Raw data read-only, logic in modules, tests on invariants, pinned dependencies, a README. That layout has outlasted every library in it.
Many people who can analyse data cannot hand their work over. Code that runs on another person’s machine is a scarce and valued skill.
At the start of the course, "it works on my machine" appeared to mean the work was finished. The central lesson is that it marks the beginning of the work, not the end.
Select the two most frequently re-run cells. Move them into src/clean.py with docstrings that say why.
Five hand-written rows covering: normal, missing, and one broken case encountered this term.
One shape invariant, one domain rule, one for the bug. Run pytest -q in a terminal, from the project folder.
Change a function so a test fails. Read the failure output, which is what a real failure will look like.
Step 4 matters: the meaning of a test is unclear until it has been seen to fail.
A clean() function works in the notebook. What is the first thing to do before relying on it?
Which of these is worth writing a test for?
pd.to_numeric converts "123" to 123pytest.approx is used.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.
The three least welcome questions are listed and answered in advance.
"That is outside what I tested" is preferable to a confident wrong answer.
What should be decided first when building a presentation?
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.
Message first, slides second, styling last. That order keeps a talk focused.
One message drives the whole deck.
| Check | Criterion |
|---|---|
| Reproducible | Another person can clone it and rerun it cleanly |
| Documented | The README + notebook explain the why |
| Honest | Cleaning choices and limitations are stated |
| Clear | One message is clear to a newcomer |
A project meeting all four is ready. These are the marks of professional data work, beyond a passing project.
A final run from a fresh clone precedes submission.
Every project follows the same sequence, and each stage has been covered.
Reproducible, documented, transparent, from the first commit.
One message, clear slides, and integrity in Q&A.
In summary: a question and a raw dataset can be turned into an answer that other people can trust.
Further work consists of practice and depth.
.py file of functions that can be imported with import.py file run from the terminal / its starting function, main()__main__ guardif __name__ == "__main__": runs only when the file is run directlyexcept: with no error named; hides real bugsdef; says whyDS 227 applies this toolkit to the full data-science method: modelling, evaluation, and more.
Running the whole pipeline, start to finish, on a dataset of personal interest.
Unused syntax is forgotten, but the workflow remains. With the practices maintained (Git, clean data, honest charts), the tools are quickly relearned.
Completed projects are the most effective form of practice.
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