DS 208 · Graduate · Week 1

Programming for Data Science

The advantages of code over manual tools, the structure of the Python data stack, and setting up a local or cloud environment.

3 units · Distance education (asynchronous online)

Outline

Three parts of about one hour each

Outline

Topics for Week 1

Key terms

Ten terms introduced this week

Memorisation is not required at this stage. Each term is explained again on the slide where it is first used, and all are collected in a glossary near the end.

script

A file of code — written instructions — that Python runs from the top line to the bottom.

e.g. a file called clean_survey.py

library

A bundle of ready-made code written by others and loaded into a new program.

e.g. pandas (tables), NumPy (numbers), matplotlib (charts)

import

The line that loads a library so that the code can use it.

e.g. import pandas as pd — load pandas, call it pd for short

notebook

A document of boxes that mix text and runnable code. Jupyter and Colab show notebooks.

e.g. week01_hello_data.ipynb

cell

One box in a notebook. Shift+Enter runs it; the result appears underneath.

e.g. a cell containing 1 + 1 shows 2

kernel

The Python program running behind a notebook. It retains everything run so far.

e.g. “Restart kernel” wipes that memory clean

variable

A name that holds a value (a piece of data), like a labelled box.

e.g. price = 100 puts 100 in a box labelled price

function

A named piece of work. It is called by writing its name and brackets; inputs go inside the brackets.

e.g. print("hi") calls the function print

error

Python stopping because it cannot carry out a line. Errors are normal, expected and fixable.

e.g. a misspelt name gives a NameError

traceback

The report printed with an error. Read the last line first: it names the problem.

e.g. NameError: name 'pirce' is not defined

Motivation

Limits of spreadsheets

In October 2020, Public Health England lost track of nearly 16,000 positive COVID-19 cases because an old Excel format truncated rows beyond its limit without any warning.

Interpretation

Spreadsheets remain suitable for small tables. The problem is that invisible, unrepeatable data handling fails silently at scale.

Clicks leave no record

A month later, no one, including the analyst, can state exactly which cells were edited, filtered or pasted.

Manual work is not repeatable

Each new monthly file requires the same 40 clicks, and each repetition can introduce a new mistake.

Size and complexity limits

Millions of rows, nested JSON, joins across ten files and statistical models exceed what a spreadsheet grid can handle.

Case study

A spreadsheet error in austerity research

Reinhart & Rogoff's influential 2010 paper "Growth in a Time of Debt" argued growth collapses when public debt passes 90% of GDP — and was cited to justify austerity worldwide. In 2013, graduate student Thomas Herndon attempted to replicate it and found, among other issues, an Excel formula that omitted five countries.

Role of replication

The error surfaced only because Herndon requested the actual spreadsheet and re-ran the analysis. No script existed to audit; the analysis existed only as cell selections.

Two implications

  • Code makes an analysis auditable: others can find its mistakes, which is an advantage
  • A graduate student with programming skills checked work that influenced economic policy; this course develops those skills
About the tool

Notebooks grew out of a 2001 project called IPython

2001

IPython

Fernando Pérez builds a better interactive Python prompt.

2011

IPython Notebook

Code, output and text together on one page in the browser.

2014

Project Jupyter

The notebook becomes its own project, named for Julia, Python and R.

2017

Google Colab

Free Jupyter notebooks that run on Google’s computers.

SourceWikipedia: Project Jupyter; IPython; Google Colab

About the tool

How widely notebooks are used

SourceNotebook counts and award: Wikipedia: Project Jupyter; downloads: pypistats.org, without mirrors, retrieved 11 Oct 2026

Part 1

Motivation for programming in data science

Three advantages: reproducibility, scale, automation.

Data analysis by clicking through a spreadsheet is assumed. This part shows what is gained when those clicks are written down as code instead.

Advantage 1

Scripts as self-documenting analyses

Code is written instructions for the computer. A script is a file of code that runs from top to bottom: a complete, ordered, re-runnable record of every step from raw file to final figure. Anyone who runs it later, including its author, obtains exactly the same result.

Writing this is not expected yet. Analogy: a script is a recipe card; each line is one step, in order, and anyone can follow it again.

  • # The whole analysis…a comment: a note for humans. Python ignores everything after #
  • import pandas as pdload the pandas library and call it pd for short
  • df = pd.read_csv(…)read the CSV file into a table and store it under the name df
  • df.dropna(subset=["program"])throw away rows where the program column is blank
  • df.groupby("program").size()count how many rows there are for each program
  • summary.to_csv(…)save those counts to a new file; print shows them on screen too
# The whole analysis, visible at a glance import pandas as pd df = pd.read_csv("enrollment_2026.csv") df = df.dropna(subset=["program"]) summary = df.groupby("program").size() summary.to_csv("per_program_counts.csv") print(summary) program MIT 3 MSDS 4 PhD CS 2 dtype: int64
Definition

Definition: reproducibility

Reproducibility (National Academies, 2019)

“Obtaining consistent computational results using the same input data, computational steps, methods, code, and conditions of analysis.”

Replicability, its neighbour

“Obtaining consistent results across studies aimed at answering the same scientific question, each of which has obtained its own data.”

Applied to the script on the previous slideReproducible?
Run it again tomorrow on the same enrollment_2026.csvyes: the same counts, every time
Repeat the filtering by hand in a spreadsheetonly if every click is remembered
Run it on another university’s enrolment filea replication: new data, same question

Source: National Academies of Sciences, Engineering, and Medicine (2019), Reproducibility and Replicability in Science, ch. 3.

Advantages 2 & 3

Scale and automation with code

Task By hand With a script
Clean 1 survey file 20 minutes of careful clicking Write once: ~15 lines
Clean 300 survey files Weeks, with drifting rules The same 15 lines in a loop
Redo everything after a data fix Start over, with no guarantee of consistency Re-run: one command
Monthly report, every month A recurring manual task Scheduled job, runs unattended
Conceptual model

Characteristics of programming work

Overview

The data science workflow

Import Tidy Transform Visualize Model Communicate the understanding loop — repeated many times

Import = get the data into Python. Tidy = arrange it so each row is one thing and each column one measurement. Transform = filter, compute and summarise. Visualize = draw it. Model = fit a statistical model. Communicate = explain the findings to others.

Review question · Part A

Identifying the missing advantage

A colleague presents an analysis: a formatted Excel workbook in which they manually filtered, copied cleaned rows to a new sheet, and built a chart. The numbers are correct. From a programming-for-data-science standpoint, what is the core problem?

A · Excel cannot make charts properly
B · The result is probably wrong
C · No one, including the author, can re-run or audit the steps
D · It should have used a more complex statistical model

Choose an answer, then click and hold (or tap) to show the answer

C — it is a reproducibility problem, not a correctness problem.

The work may be correct today, but the manual steps are invisible: they cannot be audited (Reinhart–Rogoff), re-run when data updates, or scaled to the next 300 files. The result is not wrong; it is unrepeatable.

Pause Point

  End of Part A

A suitable place to stop or take a five-minute break. Part B surveys the Python libraries used throughout the semester.

Part 2

The Python data science ecosystem

One language, with a division of labor among libraries.

Part A explained why code is written. This part shows what it is written with: one language, Python, plus a small set of libraries that each do one job.

Language choice

Why this course uses Python

Language Strengths Role in this course
Python Readable, large ecosystem, general-purpose (web, automation, ML) Course language; one language covers the whole workflow
R Statistics-oriented, strong plotting (ggplot2) Suitable to learn later if a field favors it
SQL The standard language of databases Complementary; introduced in Week 9
Julia Speed for numerical computing Growing, with a smaller ecosystem
The stack

Roles in the Python data stack

Python — the language (syntax, data structures, files) NumPy fast arrays & math pandas tables: load, clean, reshape matplotlib · seaborn visualization scikit-learn · statsmodels modeling & statistics requests · sqlalchemy data sources (Week 9) Jupyter — the workbench that runs all of it work proceeds top-down; each layer rests on the one below
Runnable code

Code runs on these slides

A code block with a ▶ Run / Edit button runs in the browser, and the code can be changed and run again. Nothing needs installing for this; the first run downloads Python into the page, which takes 10 to 20 seconds.

Printed output

The grey lines under a block are what the lecture laptop printed when it ran that exact code. Running it in the browser prints the same.

print("Hello from Python") print(2 + 3 * 4) # multiplication first, as in maths Hello from Python 14
60-second example · NumPy

Arithmetic on whole arrays

NumPy's array is a row of numbers, all of the same kind, that NumPy can do maths on in one go. It replaces the loop: the operation is written once and applies to every element (every number in the array), very fast. This idea — vectorization, one operation applied to a whole array — is the largest conceptual change from ordinary programming.

An Excel formula typed once that fills the whole column without being dragged down.

Recognition, not memorization

The goal this week is only to recognize the shape of the code. Week 5 builds fluency.

import numpy as np # monthly rainfall, mm — one array, no loops rain = np.array([12.4, 8.1, 22.7, 156.3, 301.9, 288.0]) print(rain * 0.1) # convert all values to cm print(round(rain.mean(), 1)) # the average print(rain > 100) # over 100 mm? one answer each print(rain[rain > 100]) # just the wet months [ 1.24 0.81 2.27 15.63 30.19 28.8 ] 131.6 [False False False True True True] [156.3 301.9 288. ]
  • rain = np.array([…])make an array of six rainfall numbers and name it rain
  • rain * 0.1multiply every number by 0.1 at once — no loop needed
  • rain.mean()the average of all six: about 131.6 mm
  • rain > 100ask “over 100?” of each number; each answer is True (yes) or False (no)
  • rain[rain > 100]keep only the numbers where the answer was True
Exercise · 3 min

Whole-array arithmetic

One comparison, rain > 100, asks a question of every month at once.

Tasks

  1. Predict how many months have more than 100 mm.
  2. Select ▶ Run / Edit and run the code.
  3. Change 100 to 200. Which months are left?

Result on the lecture laptop (select to reveal)

3 wet months: 156.3, 301.9 and 288.0 mm. With 200: 301.9 and 288.0.

import numpy as np rain = np.array([12.4, 8.1, 22.7, 156.3, 301.9, 288.0]) wet = rain[rain > 100] print(len(wet), "wet months:", wet) print("in cm:", rain * 0.1)
60-second example · pandas

Tables controlled by readable code

pandas puts labels on NumPy's speed. Its table is called a DataFrame: rows and named columns, like a spreadsheet controlled with code. Questions answered by clicking in Excel become one readable line each.

A CSV file (“comma-separated values”) is a plain-text table: one row per line, commas between the columns. Excel can save one; pandas can read one.

The library behind 80% of the work

Weeks 6–7 cover only pandas. Working data scientists spend most of their time in it.

  • df = pd.read_csv("…csv")read the CSV file into a DataFrame called df
  • df.groupby("barangay")["no_show"].mean()for each barangay, the average of the no_show column — a pivot table in one line
  • df[df["distance_km"] > 4]keep only the rows where distance is over 4 km
  • .sort_values("age")then put those rows in order of age
import pandas as pd df = pd.read_csv("barangay_health.csv") # the Excel pivot table, as one sentence: print(df.groupby("barangay")["no_show"].mean()) # filter + sort, still readable aloud: print(df[df["distance_km"] > 4].sort_values("age")) barangay Lahug 0.500000 Mabolo 0.333333 Talamban 0.666667 Name: no_show, dtype: float64 patient barangay age distance_km no_show 5 P06 Talamban 39 6.2 1 3 P04 Mabolo 45 4.6 1 1 P02 Lahug 61 5.5 1 6 P07 Talamban 70 7.4 1
Exercise · 3 min

One question, one line

The made-up clinic table has 8 patients in 3 barangays; no_show is 1 for a missed appointment.

Tasks

  1. Predict which barangay misses appointments most often.
  2. Select ▶ Run / Edit and run the code.
  3. Change "no_show" to "age". What does the line answer now?

Result on the lecture laptop (select to reveal)

Talamban: 0.667, two of its three patients. With "age" the line gives the mean age per barangay: Lahug 47.5, Mabolo about 41.7, Talamban about 44.0.

import pandas as pd df = pd.read_csv("barangay_health.csv") print(df.groupby("barangay")["no_show"].mean())
60-second example · matplotlib

A chart from a table in three lines

matplotlib draws; seaborn (built on top) produces well-formatted statistical plots by default. Every chart is code, so every chart is reproducible and revisable.

Charts as arguments

By Week 8, a figure is treated like a paragraph: drafted, revised and defended.

import matplotlib.pyplot as plt monthly = df.groupby("month")["visits"].sum() monthly.plot(kind="bar") plt.title("Clinic visits by month") plt.show() # the figure appears right under the code
  • import matplotlib.pyplot as pltload matplotlib’s drawing tools, nicknamed plt
  • monthly = df.groupby("month")…sum()total visits per month, from a table df loaded earlier
  • monthly.plot(kind="bar")draw those totals as a bar chart
  • plt.title(…) / plt.show()add a title, then display the finished chart
Review question · Part B

Matching a task to a layer

A CSV holds 200,000 e-wallet transactions, and the task is the average amount per province. Which layer of the stack does most of the work?

A · Raw Python — write a for-loop over every row
B · NumPy — build a numeric array per province by hand
C · pandas — read_csv, then groupby("province").mean()
D · matplotlib — it computes averages while plotting

Choose an answer, then click and hold (or tap) to show the answer

C — this is a typical pandas task: labeled table, grouped summary.

A works but is slow to write and easy to get wrong; B rebuilds what pandas already provides; D confuses drawing with computing. Matching the task to the layer is a learnable part of fluency.

Pause Point

  End of Part B

The next part is hands-on and requires a laptop and about 1 hour. It ends with a working environment, which is this week's deliverable.

Part 3

Toolkit setup

Two setup options; one is chosen this week.

Part B showed what the tools do. This part installs them on a personal computer or runs them in the browser, and ends with a first line of code and a first error message.

Setup options

Local installation versus cloud notebook

Path A · Procedure

Installing Anaconda (10–20 minutes)

Path B · Procedure

Google Colab (3 minutes)

Notebook structure

Anatomy of a Jupyter notebook

A notebook is a sequence of cells (boxes of text or code) run by a live kernel — the Python program behind the page, which remembers everything run so far. To execute or run a cell means to make Python carry it out.

Common error

Running cells out of order. The kernel's memory follows execution order, not page order; the fix is "Restart & Run All."

Markdown cells

Formatted text, headings and math that explain why. Markdown is a plain-text way to format text: # Title becomes a heading.

Code cells

Python that runs on Shift+Enter; the result prints directly below.

The kernel

The Python process holding the variables. Restarting it clears all of them, which is sometimes necessary.

Common error

Execution order and page order

A variable is a name that holds a value (a piece of data, such as the number 100). Running these three cells in the order 1 → 3 → 2 → 3 makes the "same notebook" give two different answers. The kernel records only what ran, and when.

Guideline

Before trusting or submitting a notebook: Kernel → Restart & Run All. If it errors or changes, its displayed results were not reproducible.

# cell 1 price = 100 # cell 2 price = price * 2 # run this twice by accident... # cell 3 print(price) # 200? 400? depends on history, # not on what the page shows 200
  • price = 100assignment: put the value 100 in a box labelled price. = means “store”, not “equals”
  • price = price * 2take what is in price now, double it, store it back (* means multiply)
  • print(price)call the print function: show the value on screen — 200 after one run of cell 2, 400 after two
Exercise · 2 min

Running a cell twice

Here the three cells run as one script, top to bottom, with cell 2 repeated: what an accidental second run does.

Tasks

  1. Predict what print(price) shows.
  2. Select ▶ Run / Edit and run the code.
  3. Delete the repeated line. What does it print now, and which result matches the page?

Result on the lecture laptop (select to reveal)

400: the second run doubles 200 again. Without the repeat it prints 200, the result the page appears to show.

price = 100 # cell 1 price = price * 2 # cell 2 price = price * 2 # cell 2, run a second time print(price) # cell 3
Three ways to run Python

Uses of notebooks, scripts and the REPL

Mode What it is Best for
Notebook (.ipynb) Cells + narrative + inline output Exploration, teaching, reports; the course default
Script (.py) Plain file run top to bottom Automation, reusable pipelines (Week 11)
REPL Interactive prompt, one line at a time Quick checks, such as the value a function returns
Worked example

A first cell of data work

Memorizing syntax is not required. This week's focus is the shape of the work: load, look, count.

Reading code as sentences

"Import pandas. Read the CSV into a table called df. Show the first rows. Count by region." Python code is designed to be read as sentences.

The text in quotes, "psa_population.csv", is a file path: the address of a file on the computer. A bare file name means “in the same folder as this notebook”; a path like data/psa_population.csv means “inside the data folder”.

  • df = pd.read_csv("psa_population.csv")call pandas’ read_csv function; the table it gives back is stored in df
  • df.head(3)the dot means “do this to df”: show its first 3 rows (5 without a number), to check what was loaded
  • df.shapethe table’s size as a pair: (number of rows, number of columns)
  • df["region"].value_counts()take the region column and count how many rows each region has
import pandas as pd # population estimates, one row per city (rounded, typed in for this example) df = pd.read_csv("psa_population.csv") print(df.head(3)) # peek at the first rows print(df.shape) # (rows, columns) print(df["region"].value_counts()) city region population 0 Cebu City Central Visayas 964000 1 Mandaue Central Visayas 364000 2 Lapu-Lapu Central Visayas 497000 (8, 3) region Central Visayas 4 Western Visayas 2 Eastern Visayas 2 Name: count, dtype: int64
Reading an error

Reading a traceback from the bottom up

An error is Python stopping because it cannot do what a line asks. The traceback is the structured report it prints. The last line is read first: error type, then message. The lines above show where the error occurred.

Error types this week

  • NameError — a name was used before being defined, or was misspelt
  • FileNotFoundError — wrong filename or wrong folder
  • SyntaxError — Python could not parse the line
>>> print(pirce) Traceback (most recent call last): File "cell 4", line 1, in <module> print(pirce) ^^^^^ NameError: name 'pirce' is not defined. Did you mean: 'price'? ← it even guesses
  • 1st · last line: NameError: …the error type (NameError = a name Python does not know) and the message: pirce was never defined
  • 2nd · File "cell 4", line 1where it happened: cell 4, line 1 — the line to inspect
  • 3rd · ^^^^^points at the exact part of the line Python could not handle
  • >>> print(pirce)the line that was run (>>> is the prompt where code is typed). The fix: spell it price
Exercise · 2 min

Fixing a NameError

This block fails on purpose. Its last line names the error and suggests a fix.

Tasks

  1. Select ▶ Run / Edit and run the code. Read the last line of the error first.
  2. Fix the typo.
  3. Run it again. What does it print?

Result on the lecture laptop (select to reveal)

NameError: name 'pirce' is not defined. Did you mean: 'price'? With print(price) it prints 100.

# fails on purpose: read the last line price = 100 print(pirce) NameError: name 'pirce' is not defined. Did you mean: 'price'?
Getting help

Sources of help, in order

Part 4

Course structure

Twelve weeks from no experience to a working pipeline.

Part C produced a working setup and a first error. This part explains how the rest of the course runs, and what to complete before next week.

Roadmap

Overview of the 12 weeks

Weeks Theme Topics
1–4 Python foundations This intro · types & functions · data structures & files · OOP and errors
5–7 NumPy & pandas Arrays · loading & cleaning tables · grouping, merging, reshaping
8–10 Visualization & sources matplotlib & seaborn · files, SQL & APIs · text & regex
11–12 Workflows & project Git, environments & debugging · integrative project presentations
Asynchronous format

Flexible schedule, fixed deadlines

Glossary

Week 1 terms

All new terms from this week, one line each, for reference in later weeks.

This week's lab

Week 1 lab: a preview of Weeks 2–3

The Week 1 lab runs in the browser from the course page. Replace each ____, press ▶ Run to see the output, then Check. It borrows a few ideas from the next two weeks — the lab explains each one where it is used, and later weeks cover them fully.

Mastery of these terms is not expected yet. The goal this week is to press Run, read the output, and fix one small thing at a time.

Terms introduced in the lab

list
an ordered collection of values: [28, 31, 29] (Week 3)
index
an item’s position in a list, counted from 0 (Week 3)
loop
code that repeats a block once per item (Week 2)
string
text inside quotes: "Ana" (Week 2)
f-string
a string starting with f that fills in values from { }
return
how a function hands its answer back (Week 2)
Preparation for next week

Week 1 checkpoint

One goal: a working environment with proof.

1 · Set up an environment

Install Anaconda (Path A) or sign in to Google Colab (Path B) — links on the course page.

2 · Run the starter notebook

Download week01_hello_data.ipynb from the course page and run every cell top-to-bottom.

3 · Submit the proof

Upload the executed notebook (every cell run, so each result shows underneath it) to the submission portal, and post an introduction in the forum: field, data of interest, and Python experience (none is acceptable).

Synthesis

Three main points

Resources

Free references

Core companions (free online)

McKinney, Python for Data Analysis (wesmckinney.com/book) — by pandas' creator. · VanderPlas, Python Data Science Handbook (jakevdp.github.io/PythonDataScienceHandbook).

Documentation

docs.python.org (the official tutorial) · pandas.pydata.org/docs · Colab's own intro notebooks at colab.research.google.com.

Next Week

Python fundamentals I

Types, control flow and functions: the grammar of every Python script. A working environment is required.

DS 208 · Programming for Data Science