Cleaning it
Last updated
Official data is cleaner than most, and still never ready to analyse as it comes: wide tables, region names spelt three ways, marks for missing values, a definition that changed one year. In this lesson you'll write the capstone's cleaning script, with every step a function, checks that stop it when something's wrong, and a cleaning log that says what was changed and why.
By the end of this lesson you can
- Write a cleaning pipeline as a script of small, named steps
- Add checks that fail loudly when the data breaks an assumption
- Keep a cleaning log of every decision
What needs doing
Start from the "Known problems" list on your source card (C.1, C.2). Go through the usual suspects, and tick each one when you've looked, whether or not it needed a fix:
Write what you found for each in the cleaning log (step 4).
The last one is easy to miss and matters most. Official series sometimes change how they're measured: a new list of markets, a new kind of rice, a new rule for counting pupils, a station moved. The numbers continue without a gap, but the before and after aren't the same measure. The publisher's notes usually say so.
The pipeline
Put the cleaning in a script, clean.py, not a notebook: it's run, not read, and C.10 reruns it from scratch. Each step is a small function with a name that says what it does, chained with .pipe (5.10). Here's a starting point for the rice question. The column names and the month format are examples: use the ones your file has.
"""Clean the PSA retail rice prices: data/raw → data/clean.""" from pathlib import Path import pandas as pd RAW = Path("data/raw/rice_retail_2018_2025.csv") CLEAN = Path("data/clean/rice.csv") REGIONS = pd.read_csv("data/regions.csv") # region name as PSA writes it → PSGC code def read(path): return pd.read_csv(path, encoding="utf-8-sig", skiprows=2, na_values=["..", "-"]) def tidy(df): long = df.melt(id_vars=["Geolocation", "Commodity"], var_name="month", value_name="price") long.columns = ["region", "rice", "month", "price"] long["month"] = pd.to_datetime(long["month"], format="%Y %B") return long def add_codes(df): out = df.merge(REGIONS, on="region", how="left", validate="many_to_one") unmatched = out.loc[out["psgc"].isna(), "region"].unique() assert len(unmatched) == 0, f"regions with no PSGC code: {unmatched}" return out def check(df): assert df["price"].dropna().between(20, 120).all(), "a price outside ₱20 to ₱120" assert not df.duplicated(["psgc", "rice", "month"]).any(), "duplicate region, rice and month" print(f"{len(df)} rows, {df['price'].isna().sum()} missing prices, " f"{df['month'].min():%b %Y} to {df['month'].max():%b %Y}") return df if __name__ == "__main__": df = read(RAW).pipe(tidy).pipe(add_codes).pipe(check) CLEAN.parent.mkdir(exist_ok=True) df.to_csv(CLEAN, index=False)
tidyturns the month columns into rows (4.4), so the result is tidy: one row per region, kind of rice and month.add_codesjoins a small lookup table you write by hand,data/regions.csv, with every spelling of each region the source uses and its PSGC code (5.8). Hand-written lookups belong in the project (and in git); they're part of the method, not the data.validate="many_to_one"(4.3) stops the join if the lookup has a region twice.- Missing prices stay missing. Filling them is an analysis decision, made in C.5, where it can be seen.
Run it: python clean.py. It writes data/clean/rice.csv and prints a one-line summary.
Checks
Every assumption your analysis makes about the data should be a check in the script (5.9), so that next year's download, or a revision, can't quietly break it:
- Every place matched a code. A new region name in the source (a renamed or new region) should stop the script, not drop rows.
- Values are in a sensible range. A retail price of ₱4 or ₱400 a kilo is a typing error or a unit change.
- No duplicates on the columns that should identify a row.
- The months run without gaps, or the gaps are the ones you know about.
When a check fails, read the message, look at the rows, and decide: fix it in code, or keep it and write it down. Never loosen a check just to make it pass.
The reference analysis of the rice question needed one more check than this list, and found out the hard way. PSA's rice table marks a month not yet published with ., and its CPI table with ... Read with the rice table's setting, the CPI column came in as text, every range check still passed, and nothing failed until much later. Now a type check stops it at once:
data-capstone/rice/clean.py, lines 107–117def load_cpi(): # This table marks a month not published yet with "..", not ".". table = pd.read_csv(RAW / "psa_cpi.csv", na_values=[".."]) # The CPI table has one row the rice table doesn't: areas outside NCR. table = table[~table["Geolocation"].str.contains("Areas Outside")] long = to_long(table, CPI_TABLE_NAMES, "cpi") long["month"] = pd.to_datetime(long["when"], format="%Y %b") assert long["cpi"].dtype == "float64", "a CPI value that isn't a number" long = long.dropna(subset=["cpi"]) print(f"CPI: {len(long)} rows, 2018 = 100, {long['month'].min():%B %Y} to {long['month'].max():%B %Y}") return long[["psgc", "month", "cpi"]]
The cleaning log
Every decision goes in CLEANING.md, beside the script: what was changed, and why. A reader of your report should be able to find out exactly what you did to the publisher's numbers.
# Cleaning log (example entries) | date | step | what | why | |---|---|---|---| | 2 Mar 2026 | read | skiprows=2 | two title lines above the header | | 2 Mar 2026 | read | ".." and "-" as missing | OpenSTAT's marks for not available | | 2 Mar 2026 | add_codes | "Region IV-A" and "CALABARZON" both → one code in regions.csv | if the source uses both names | | 3 Mar 2026 | check | kept 6 missing months for one region | missing in the source; not filled (C.5 decides) |
A script can write most of the log itself, by printing what it changed as it goes. Here's what the reference's schools/clean.py printed. It found two counts PSA marks as not available, and two totals that don't equal their parts because of them:
read 480 cells: 146 marked '...' (doesn't apply), 2 marked '..' (not available) not available: SUCs/LUCs, Elementary, 2000-2001 not available: SUCs/LUCs, Junior High School, 2000-2001 checked the 'Total' rows against the parts: 2 differ 2000-2001, Elementary: the total is 16,096 more than the parts (a part is '..' that year) 2000-2001, Junior High School: the total is 69,537 more than the parts (a part is '..' that year) wrote data/clean/enrolment.csv: 252 rows, school years 2000-2001 to 2023-2024
Commit clean.py, regions.csv and CLEANING.md together (10.5), with a message saying what the cleaning does.
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.
- pandas: DataFrame.pipe: chaining functions that take and return a DataFrame
- pandas: DataFrame.melt: turning month columns into rows
- Philippine Statistics Authority: Philippine Standard Geographic Code: official region names and codes
- Wickham, Tidy Data (Journal of Statistical Software, 2014): one row per observation, one column per variable