Getting it
Last updated
Getting the data is the first step that can't be undone by rerunning code, so it's the one to record most carefully. In this lesson you'll set up the project, download or receive the data, save it in data/raw exactly as it came, write down where and when you got it, and read it into pandas for the first time without changing it.
By the end of this lesson you can
- Set up a capstone project folder and environment
- Save raw data unchanged, with a record of where and when it came from
- Read an official table into pandas and check it arrived whole
The project
Make a new folder for the capstone, with the layout from 10.4, a fresh environment, and git from the start (10.5):
cd Documents mkdir capstone cd capstone mkdir data, data\raw, data\clean, reports py -m venv .venv .venv\Scripts\activate (.venv) $ python -m pip install pandas matplotlib seaborn statsmodels jupyterlab nbconvert streamlit (.venv) $ python -m pip freeze > requirements.txt (.venv) $ git init
Add a .gitignore straight away, before the first commit: .venv/, .env, data/ and reports/. Even when the data's licence allows sharing, keep it out of git; you'll publish the clean version properly in C.9.
Download, and keep the original
For PSA data (the rice and schools questions): on OpenSTAT, find your table, choose the variables (regions, commodities, months), and save it as CSV with a heading. Note every choice you made: someone repeating your work needs to make the same ones. If the table is large, OpenSTAT may limit how much comes at once; download in parts (by year, say) and keep each file.
For the rain question: find a station in GHCN-Daily's station list (ghcnd-stations.txt; Philippine codes start with RP), and download its file from the access folder: one CSV per station, every day it has, rainfall in tenths of a millimetre. Check the years it covers before you commit to it: many stations are complete for decades, then patchy. For CHIRPS, download the Philippine file from the Humanitarian Data Exchange: one CSV, every province and region, every ten days since 1981. Keep it whole in data/raw/, or keep the rows for your station's province, copied unchanged, and record the whole file's fingerprint.
Downloading by script beats clicking: it records every choice you made, and you can run it again. OpenSTAT has an API for exactly this. The reference analysis gets all its data that way:
data-capstone/get_data.py, lines 41–67def psa_table(path, query): """Ask OpenSTAT's PXWeb API for part of a table, as CSV.""" body = json.dumps({"query": query, "response": {"format": "csv"}}).encode() request = urllib.request.Request(PSA + path, data=body, headers={**HEADERS, "Content-Type": "application/json"}) with urllib.request.urlopen(request, timeout=120) as response: return response.read() def pick(code, values): return {"code": code, "selection": {"filter": "item", "values": values}} def get_rice(): months = [str(m) for m in range(12)] # January to December, not the annual average save("rice/psa_rice_retail_prices.csv", psa_table( "2M/2018NEW/0042M4ARN01.px", [pick("Geolocation", REGIONS), pick("Commodity", ["0", "1"]), pick("Period", months)], )) # Consumer price index, all items, for the country and each region. meta_url = urllib.request.Request(PSA + "2M/PI/CPI/2018NEW/0012M4ACP22.px", headers=HEADERS) meta = json.load(urllib.request.urlopen(meta_url, timeout=120)) places = meta["variables"][0] regions = [v for v, t in zip(places["values"], places["valueTexts"]) if not t.startswith("....")] save("rice/psa_cpi.csv", psa_table( "2M/PI/CPI/2018NEW/0012M4ACP22.px", [pick("Geolocation", regions), pick("Commodity Description", ["0"]), pick("Period", months)], ))
Every request names the table and the values wanted from each variable, and the answer is saved exactly as it arrives.
Either way:
- Save the file in
data/raw/, and never edit it. Not even to delete a blank row. Make it read-only. - Give it a name that says what it is and what it covers:
rice_retail_2018_2025.csv, notdownload (3).csv. - If you download again later (for newer months), keep the old file and add the new one beside it. Official figures are sometimes revised, and you'll want to know which version a result came from.
Record where and when
Write data/raw/SOURCES.md, one section per file:
# Raw data ## data/raw/rice_retail_2018_2025.csv - From: Philippine Statistics Authority, OpenSTAT - Table: (the table's title, exactly as OpenSTAT shows it) - Choices made: all regions; regular-milled and well-milled rice; every month, January 2018 to the latest - Saved as: CSV, comma delimited, with heading - Downloaded: 2 March 2026, by (your name) - Licence: CC BY (OpenSTAT terms of use) - SHA-256: 3f1c... (from fingerprint.py) - Notes from the publisher: (copy the table's footnotes here)
The SHA-256 fingerprint is a long code computed from every byte of the file. If even one character changes, the fingerprint changes completely. Put this in fingerprint.py and run it:
from hashlib import sha256 from pathlib import Path for path in sorted(Path("data/raw").iterdir()): print(path.name, sha256(path.read_bytes()).hexdigest())
Copy each fingerprint into SOURCES.md. Anyone with the file can check it's the same one you used; if a raw file is ever edited by accident, the fingerprint shows it.
A first read
Read the file in a notebook, 02-get.ipynb, without changing anything yet. Look at the raw text first (3.3): official CSV exports often have title lines above the header, notes below the data, and their own marks for missing values. The code below is a starting point; your file will need its own skiprows and na_values:
from pathlib import Path import pandas as pd raw = Path("data/raw/rice_retail_2018_2025.csv") print(raw.read_text(encoding="utf-8-sig")[:600]) # look at the text first (3.3) df = pd.read_csv(raw, encoding="utf-8-sig", skiprows=2, na_values=["..", "-"]) print(df.shape) df.head()
Then check it arrived whole, and write the answers down in the notebook:
- How many rows and columns, and does that match what you chose? With months as columns, it should be one row per region per kind of rice.
- What are the column names? Months as columns (wide) will need reshaping (4.4) in C.3.
- What marks missing values?
..,-, blanks, or zeros that mean "not collected"? - Do the first and last values match what the website showed? Check two or three cells by eye.
Don't fix anything here. Every problem you find goes on the source card's "Known problems" list, for C.3.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Philippine Statistics Authority: OpenSTAT: tables can be chosen by variable and saved as CSV or Excel
- pandas: read_csv: encoding, skiprows, na_values
- Python: hashlib: SHA-256 fingerprints of files
- NOAA NCEI: GHCN-Daily files: the station list, the file layout, units, and the quality flags