DS 227 · Week 6

Data Preprocessing II

Integration, transformation and reduction: combining tables, reshaping values, and reducing large data to a manageable size.

Knowledge Discovery in Data · University of the Philippines Cebu

Outline

Combining tables into one, then reducing it

Previous session

Clean data spread across several sources

Sales in one file, city metadata in another, last month's records in a third. Analysis needs them in one frame, at one grain (what one row stands for), in comparable units. This session covers how to achieve that.

Why data arrives scattered

Different systems, owners and months. No source provides the analysis table; the analyst builds it.

Where it can go wrong

Joins that drop rows without warning, duplicates that double totals, and labels that almost match. None of these raises an error.

About the tool

Joins come from a 1970 paper on tables

1970

Relational model

Edgar F. Codd at IBM proposes keeping data in tables linked by shared keys.

1974

SEQUEL

IBM researchers design a language to query those tables; it becomes SQL.

1979

Oracle

One of the first commercial SQL databases goes on sale.

1981

Turing Award

Codd is honoured for his contributions to database theory and practice.

SourceWikipedia: Edgar F. Codd; Wikipedia: SQL

About the tool

How widely relational tables are used

SourceDB-Engines ranking, October 2026; pandas: Merge, join, concatenate

Key terms · 1 of 2

Eight terms for Parts A and B: combining and reshaping

concatenate

Join tables end to end: the rows of one go under the rows of the other.

e.g. pd.concat([jan, feb])

key

The column two tables share, used to decide which rows belong together.

e.g. city, or a project’s contract_id

merge / join

Put two tables side by side by matching their key values, like Excel’s VLOOKUP.

e.g. pd.merge(sales, meta, on="city")

inner / left / outer join

Which rows survive a merge: only matches; every row of the left table; everything.

e.g. how="left"

derived column

A new column computed from existing ones.

e.g. duration = completion date − start date

scaling

Rescaling columns so that columns with large numbers do not dominate those with small numbers.

e.g. pesos in millions next to percent

normalisation

The min–max kind of scaling: smallest value → 0, largest → 1.

e.g. (x - x.min()) / (x.max() - x.min())

encoding (one-hot)

Turning a text category into numbers: one 0/1 column per category.

e.g. status_Completed = 1 or 0

Key terms · 2 of 2

Seven terms for Part C: reducing the data

binning

Sorting numbers into ranges (bins) so that they can be counted as categories.

e.g. duration → “<3mo”, “3-12mo”…

aggregation

A summary that turns many values into one: sum, count, mean.

e.g. one total per region

grain

What one row stands for: a project, a region, a region-year.

e.g. 34,079 project rows vs 18 region rows

long vs wide

Long: one measurement per row. Wide: a grid with one category across the columns.

e.g. region-year rows vs a years-across table

dimensionality reduction

Keeping fewer columns while losing as little information as possible.

e.g. dropping a column that is 0 on every row

sampling

Taking a random subset of rows to look at.

e.g. df.sample(500, random_state=42)

random seed

A fixed starting number for random picks, so the same “random” rows come back every time.

e.g. random_state=42

Runnable code

Code on these slides runs in the browser

A code block with a ▶ Run / Edit button opens in an editor. The code can be changed and run again; Reset restores the original. This week’s exercises work this way.

First run

The first run downloads Python and pandas into the page, which takes 10 to 20 seconds. Blocks that download the flood data have no button: the companion notebook runs those.

Key terms

browser Python
a complete Python (called Pyodide) running inside the web page; nothing is installed and the code is not sent to a server
object
the browser’s pandas 2.2 name for a text column; pandas 3, on the lecture laptop, calls it str
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
  • sys.maxsize > 2**32True on the laptop’s 64-bit Python, False in the browser’s 32-bit one
  • t.dtypeseach column’s type: str on the laptop, object in the browser
Part A

Integration

Two operations: stacking rows, or joining columns on a key.

Last week covered cleaning one table. This part combines several: putting tables under each other, or side by side by matching a shared column.

Operation 1 · Stack

Stacking rows from tables with the same columns

Two months of records with identical columns belong one above the other, which is what pd.concat does. To concatenate is to join end to end: here, the February rows go under the January rows.

Purpose of ignore_index=True

Without it, both frames keep their own 0, 1 labels, and a frame with duplicate index labels causes errors later (.loc[0] returns two rows).

jan = pd.DataFrame({"city": ["Cebu", "Davao"], "sales": [10, 22]}) feb = pd.DataFrame({"city": ["Cebu", "Iloilo"], "sales": [14, 9]}) both = pd.concat([jan, feb], ignore_index=True) print(both) city sales 0 Cebu 10 1 Davao 22 2 Cebu 14 3 Iloilo 9
  • jan, febtwo small tables with the same two columns, city and sales
  • [jan, feb]a list of the tables to stack, in order: January first
  • ignore_index=Truenumber the rows afresh, 0 to 3 (the row labels are the index)
Exercise · 3 min

Joining tables with different facts on a key

sales holds the numbers; meta (data about the cities) holds the regions of Cebu, Iloilo and Baguio. The city column is the key: the column both tables share, used to match rows. A merge (databases say join) puts the matching rows side by side.

Tasks

  1. Predict Davao’s region after the merge.
  2. Select ▶ Run / Edit and run the code.
  3. Change how="left" to how="inner". Which row disappears?

Result on the lecture laptop (select to reveal)

Davao’s region is NaN, because meta has no Davao row. With how="inner", Davao’s row is removed and 2 rows remain: Cebu and Iloilo.

Excel’s VLOOKUP, which looks up each sales row’s city in the other table and copies the region across.

sales = pd.DataFrame({"city": ["Cebu", "Davao", "Iloilo"], "sales": [24, 22, 9]}) meta = pd.DataFrame({"city": ["Cebu", "Iloilo", "Baguio"], "region": ["Visayas", "Visayas", "Luzon"]}) merged = pd.merge(sales, meta, on="city", how="left") print(merged)
  • pd.merge(sales, meta, …)the left table first, then the right table
  • on="city"the key: match rows whose city is the same
  • how="left"keep every row of the left table, matched or not
The how= parameter

Rows retained by each join type

sales city sales Cebu 24 Davao 22 Iloilo 9 meta city region Cebu Visayas Iloilo Visayas Baguio Luzon how="left" city sales region Cebu 24 Visayas Davao 22 NaN Iloilo 9 Visayas 3 rows how="inner" city sales region Cebu 24 Visayas Iloilo 9 Visayas 2 rows how="outer" city sales region Baguio NaN Luzon Cebu 24 Visayas Davao 22 NaN Iloilo 9 Visayas 4 rows every sales row; Davao’s region is NaN only cities in both: Davao is gone everything: Baguio arrives with no sales
Worked example

Join types and the question each answers

The choice is not stylistic. It determines which rows remain, and therefore which population the conclusion describes.

Default: how="left" during exploration

It keeps the main table intact and shows unmatched keys as NaN instead of deleting them.

  • how="inner"only the cities found in both tables: Davao’s row is dropped, without a warning
  • indicator=Trueadds a column _merge saying where each row matched: both or left_only
  • m[m._merge == "left_only"]the rows that found no partner
# sales, meta: the two tables from the join exercise print(len(pd.merge(sales, meta, on="city", how="left"))) print(len(pd.merge(sales, meta, on="city", how="inner"))) m = pd.merge(sales, meta, on="city", how="left", indicator=True) print(m[m._merge == "left_only"]) 3 2 city sales region _merge 1 Davao 22 NaN left_only
Worked example

A repeated key multiplies rows

A key should name each row once. When the lookup table lists Cebu twice, the merge keeps both matches: Cebu’s sales appear twice and the total grows from 55 to 79, with no error.

The row count as a warning sign

Print len() before and after every join. An unexpected increase means totals are double-counted and every later percentage is wrong.

# Cebu listed twice in the lookup table dup = pd.DataFrame({"city": ["Cebu", "Cebu", "Iloilo"], "region": ["Visayas", "Visayas", "Visayas"]}) print(dup.city.is_unique) merged = pd.merge(sales, dup, on="city", how="left") print(len(sales), "rows ->", len(merged), "rows") print(merged.sales.sum(), "instead of", sales.sales.sum()) False 3 rows -> 4 rows 79 instead of 55
  • dup.city.is_uniqueFalse: some city appears more than once, so city is not a safe key
  • 3 rows -> 4 rowsone extra row from the second Cebu match
Worked example

Combining sources creates duplicates

When the same record arrives from two files, Cebu's sales are counted twice. drop_duplicates() keeps one copy of each fully identical row. (A duplicate, from week 5: a row identical to an earlier one.)

records = pd.DataFrame({"city": ["Cebu", "Cebu", "Davao", "Cebu"], "year": [2024, 2024, 2024, 2025], "sales": [24, 24, 22, 30]}) clean = records.drop_duplicates() print(clean) city year sales 0 Cebu 2024 24 2 Davao 2024 22 3 Cebu 2025 30

Common error: subset=

drop_duplicates(subset=["city"]) would merge 2024 and 2025 Cebu into one row, deleting a real year of data. Matching should use all the columns that define "the same record," not fewer.

Case study

The flood data, loaded from the course API

The checks so far used small tables typed on the slides. From here they meet real data: the 34,079 flood control projects from weeks 4 and 5, downloaded in one request.

Why not pd.read_csv(url)?

pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.

The browser cannot download the data, so this block has no Run button; the companion notebook runs it.

import io, requests url = "https://portal.latarak.com/api/flood/export.csv" resp = requests.get(url, timeout=60) df = pd.read_csv(io.StringIO(resp.text)) print(df.shape) (34079, 15)
  • requests.get(url)download the whole table in one request: export.csv is the bulk endpoint used in week 5
  • pd.read_csv(io.StringIO(resp.text))read the downloaded text as if it were a file
  • (34079, 15)34,079 projects, 15 columns; from here on df is the flood table
Before any join

Verifying that the key is unique

A key should name each row once (a primary key). A join multiplies rows without warning when the key repeats. A short check here prevents doubled totals later.

The flood data passes

34,079 ids for 34,079 rows. This is a valid primary key; it should be confirmed, not assumed.

print(df.contract_id.nunique(), len(df)) # if they were not equal, list the repeats: repeats = df[df.contract_id.duplicated(keep=False)] print(repeats.shape) 34079 34079 (0, 15)
  • .nunique()how many different values the column holds
  • 34079 34079as many different ids as rows: no id repeats
  • duplicated(keep=False)mark every copy of a repeated id, not only the second one; (0, 15) means none
Review question

Question (select to reveal the answer)

A left join of 100 sales rows to a city table returns 130 rows. What happened?

A · Impossible — left joins never add rows
B · Some cities appear more than once in the right table, so rows multiplied
C · pandas added 30 blank rows for safety
D · ignore_index was forgotten

B: duplicate keys multiply rows.

A left join keeps every left row at least once, but a key that matches three right-table rows appears three times. Sums over that frame are inflated without warning, which is why row counts are checked.

Break

  Five minutes

Next: making the values usable.

Part B

Transformation

With the table assembled, the values are shaped to fit the question.

With one table in place, this part changes its values: the right data types, consistent labels, new columns computed from old ones, numbers on a common scale, and categories turned into numbers.

Exercise · 3 min

Numbers stored as text cannot be used in calculations

Scraped and merged data often arrives as strings: "31", "1,204", "2024-01-05". Types are corrected before any arithmetic.

Tasks

  1. Predict which of the three sales values become NaN.
  2. Select ▶ Run / Edit and run the code.
  3. Change "1,204" to "1204" and run again. What changes?

Result on the lecture laptop (select to reveal)

"1,204" and "n/a" both become NaN: a comma is not part of a number to to_numeric, and coerce turns every failure into NaN. With "1204" the value converts to 1204.0 and only "n/a" stays NaN.

raw = pd.DataFrame({"sales": ["31", "1,204", "n/a"], "date": ["2024-01-05", "2024-02-11", "2024-03-02"]}) raw["sales"] = pd.to_numeric(raw["sales"], errors="coerce") raw["date"] = pd.to_datetime(raw["date"]) print(raw) print(raw.dtypes)
  • pd.to_numeric(…, errors="coerce")text → numbers; anything unreadable becomes NaN instead of an error
  • pd.to_datetime(…)text like "2024-01-05" → real dates that can be subtracted and sorted
Worked example

A CSV file stores characters, not types

When the file is read without pandas (Python’s built-in csv reader), every column is a string (text), including the ones that look like money.

Consequence

Sorting text puts ₱9M above ₱80M, because "9" > "8". A "top projects" list would be wrong, and no error would be raised.

import csv, io text = "contract_id,budget,year\nP-001,279839557.31,2022\n" rows = list(csv.DictReader(io.StringIO(text))) print(repr(rows[0]["budget"])) print(repr(rows[0]["year"])) print(sorted(["9000000", "80000000"])) '279839557.31' '2022' ['80000000', '9000000']
  • rowsthe text read by csv.DictReader: a list with one dictionary (column name → value) per line
  • repr(…)print a value with its quote marks: '279839557.31' is text (a str), not a number
  • sorted([…])puts values in order; text is ordered character by character, like words in a dictionary
Conversion

errors="coerce" converts failures into countable NaNs

Forcing a type on unclean data either raises an error or produces wrong values without warning. coerce offers a third option: failures become visible and countable.

Count before and after

If isna().sum() increases after a conversion, those rows held non-numeric values and should be inspected.

df["budget"] = pd.to_numeric(df.budget, errors="coerce") print(df.budget.isna().sum()) # failed to convert for col in ["start_date", "completion_date"]: df[col] = pd.to_datetime(df[col], errors="coerce") print(df[["start_date", "completion_date"]].isna().sum()) 0 start_date 973 completion_date 6414 dtype: int64
  • df["budget"] = …replace the column with its converted version
  • .isna().sum()count the NaNs after converting: new ones are values that failed to convert
  • 973, 6414dates already blank in the file: 973 projects have no start date and 6,414 no completion date
Purpose of a derived column

A derived column answers a question and checks the data

duration = completion_date − start_date

Derived column

Two date columns become one number

A derived column is one computed from other columns. The duration of a flood control project is not a column in the data. It must be computed, which takes one line once the types are correct.

27,664 projects have a duration

The rest are missing one of the two dates, which, as shown last week, means they are unfinished.

df["duration"] = (df.completion_date - df.start_date).dt.days print(df.duration.describe().round()) count 27664.0 mean 233.0 std 159.0 min -17.0 25% 139.0 50% 202.0 75% 284.0 max 2688.0 Name: duration, dtype: float64
  • completion_date - start_datesubtracting two dates gives a length of time
  • .dt.days.dt reaches date parts; .days turns each length into a whole number of days
  • count 27664.0only rows with both dates get a duration; the rest are NaN
The minimum

A project that finished before it started

The median is a sensible 202 days. The maximum, 2,688 days, is a long project but a possible one. The minimum is −17, and that is not possible at all.

One row in 27,664

Such a row is practically impossible to find by eye. The derived column revealed it as soon as .describe() was called.

cols = ["contract_id", "status", "start_date", "completion_date", "duration", "region"] print(df.loc[df.duration < 0, cols].iloc[0]) contract_id 16DC0070 status Completed start_date 2016-05-23 00:00:00 completion_date 2016-05-06 00:00:00 duration -17.0 region Region IV-A Name: 27601, dtype: object
  • df.loc[df.duration < 0, cols]rows where the test is True, and only the columns named in cols
  • .iloc[0]the first (here the only) such row, printed down the page, one column per line
  • 00:00:00 / -17.0dates carry a time of day (midnight); the duration is a decimal because the column also holds NaN
General lesson

Neither source column is wrong on its own

Guideline

A range check for every derived column

The check belongs in the same cell as the calculation, where the meaning of "impossible" for that quantity is still clear.

Three questions per derived column

Whether it can be negative, whether there is a physical maximum, and how many rows violate either.

  • assert bad == 0, "…"assert checks a claim; if it is False, the program stops with the given message
  • AssertionError: 1 negative durationsread the last line of the error: the type (a failed assert) and the message
# fails on purpose: read the last line df["duration"] = (df.completion_date - df.start_date).dt.days # range check, in the same cell bad = (df.duration < 0).sum() assert bad == 0, f"{bad} negative durations" AssertionError: 1 negative durations
Exercise · 3 min

"Cebu City" ≠ "cebu" ≠ "CEBU "

To a reader, one place. To merge and groupby, separate keys. Labels are harmonized before integration.

Tasks

  1. Predict both counts of different labels.
  2. Select ▶ Run / Edit and run the code.
  3. Remove the .replace(…) line and run again. How many labels now?

Result on the lecture laptop (select to reveal)

4 labels before, 2 after: cebu and davao. Without .replace there are 3, because "cebu city" is still a different label from "cebu".

  • .str.strip()remove spaces at both ends of each text value
  • .str.lower()make every letter small
  • .replace({"cebu city": "cebu"})swap one spelling for another, using a dict: old → new
cities = pd.Series(["Cebu City", "cebu", "CEBU ", "Davao"]) print(cities.nunique()) clean = (cities.str.strip() .str.lower() .replace({"cebu city": "cebu"})) print(clean.nunique()) print(clean.tolist())
Categories

Verifying labels before grouping

A groupby treats "Cebu" and "cebu " as two different places. The flood data is clean, but this is known only because it was checked.

18 regions, all consistent

No case variants, no stray whitespace. This one-line check applies to any column used for grouping.

print(df.region.nunique()) # normalise, then count again print(df.region.str.strip().str.lower().nunique()) 18 18
Exercise · 3 min

Deriving the column the question requires

Raw columns record what was measured. Derived columns express the question: a rate, a ratio, a flag (a True/False column), an age from a date.

Tasks

  1. Predict which city ranks last per 100,000 people.
  2. Select ▶ Run / Edit and run the code.
  3. Compare with the ranking by raw sales. Which cities swap places?

Result on the lecture laptop (select to reveal)

Davao: second by sales (22) but last per person, with 1.24 sales per 100,000 people against Iloilo’s 1.97. Iloilo and Davao swap places; Cebu stays first.

Importance of per-capita values

Raw totals mostly measure city size. Dividing by population gives a fair comparison, which can reorder the ranking.

cities = pd.DataFrame({"city": ["Cebu", "Davao", "Iloilo"], "region": ["Visayas", "Mindanao", "Visayas"], "sales": [24, 22, 9], "population": [964_000, 1_777_000, 457_000]}) cities["per_100k"] = cities["sales"] / cities["population"] * 100_000 cities["is_visayas"] = cities["region"] == "Visayas" print(cities[["city", "sales", "per_100k", "is_visayas"]].round(2))
  • cities["sales"] / cities["population"] * 100_000sales per 100,000 people: a rate, comparable across city sizes
  • cities["region"] == "Visayas"a flag: True or False on every row
Fair comparison

Putting columns on the same scale before comparison

Pesos in the millions next to percentages in single digits: any distance or average across them is dominated by the column with larger numbers. Scaling (rescaling each column to a common range) puts them on equal footing.

When a height in centimetres is compared with a weight in tonnes, the larger numbers dominate unless both are first converted to “how large for its kind”.

Min–max (normalisation)

Normalisation rescales each column to 0–1: (x − min) / (max − min). It is simple and bounded but sensitive to outliers.

Z-score

Center at 0, spread of 1: (x − mean) / std. It measures how unusual a value is within its own column.

When it matters

Whenever columns are combined or compared across units. Clustering and modeling in later DS courses depend on it.

Categories as numbers

One-hot encoding: one yes/no column per category

Many methods only accept numbers. Encoding turns a text category into numbers. One-hot encoding makes one new column per category, holding 1 where the row is that category and 0 elsewhere. On the flood data, pd.get_dummies(df.status) gives every project five such columns, one per status.

A checklist with one box per option, where exactly one box is ticked on each row.

Reason not to number them 1, 2, 3

Numbering would make “On-Going” (2) count as twice “Completed” (1), implying an order and a distance that the categories do not have.

t = pd.DataFrame({"city": ["Cebu", "Davao", "Iloilo"], "status": ["Completed", "On-Going", "Completed"]}) print(pd.get_dummies(t, columns=["status"], dtype=int)) city status_Completed status_On-Going 0 Cebu 1 0 1 Davao 0 1 2 Iloilo 1 0
  • pd.get_dummies(…)pandas’ one-hot encoder (“dummy” columns is another name)
  • columns=["status"]encode this column; city is left alone
  • dtype=intwrite 1 and 0 instead of True and False
Part C

Reduction

Not every column or row is needed.

The table now has the right values. This part reduces it deliberately: fewer columns, fewer rows, or fewer distinct values.

Reducing width

Selecting the columns the question requires

Internal IDs, empty notes and audit fields are not needed for an analysis of sales by region. A column list is the simplest reduction there is.

cities = pd.DataFrame({"city": ["Cebu", "Davao", "Iloilo"], "region": ["Visayas", "Mindanao", "Visayas"], "sales": [24, 22, 9], "internal_id": ["A17", "B02", "C99"], "notes": ["", "", ""]}) keep = cities[["city", "region", "sales"]] print(cities.shape, "->", keep.shape) (3, 5) -> (3, 3)
  • cities[["city", "region", "sales"]]a list of the columns to keep; internal_id and notes are left out

Reversibility

Dropping from the working frame is reversible because of week 5's rule: the raw file still has everything. Copies are reduced, never sources.

Risk

A dropped column may be the confounder needed in week 9. When in doubt, keep it: storing columns costs little, and re-collecting data costs much more.

Fewer dimensions

A constant column carries no information

Each column is one dimension of the data. Dimensionality reduction means keeping fewer columns while losing as little information as possible. The simplest case is a column with one value on every row.

Week 4’s example

amount_paid has a single value, 0, on all 34,079 rows. It cannot tell one project from another, so it can be removed from the working copy.

Further study

Methods such as PCA combine many related columns into a few new ones. The idea is the same, with more mathematics; it is covered in ML courses.

print(df.nunique().sort_values().head(4)) lean = df.drop(columns=["amount_paid"]) print(df.shape, "->", lean.shape) amount_paid 1 status 5 year 11 category 17 dtype: int64 (34079, 16) -> (34079, 15)
  • df.nunique()for every column, how many different values it holds
  • .sort_values().head(4)the four columns with the fewest different values
  • amount_paid 1one value everywhere: no information
  • df.drop(columns=[…])a new table without that column; the raw file keeps it
Stack and join

Concatenating adds rows; merging adds columns

Both "combine two tables". They change the shape in opposite ways, and the row count shows which one was applied.

Checking the arithmetic

After a concat, rows should be the sum of the inputs. After a merge, columns should be the sum minus the shared key.

# same columns, more rows y2024 = df[df.year == 2024] y2025 = df[df.year == 2025] both = pd.concat([y2024, y2025]) print(len(y2024), "+", len(y2025), "->", both.shape) # same rows, more columns: each project gets its region's count counts = df.region.value_counts().rename("region_projects").reset_index() wider = df.merge(counts, on="region", how="left") print(df.shape, "->", wider.shape) 5553 + 3475 -> (9028, 16) (34079, 16) -> (34079, 17)
  • pd.concat([y2024, y2025])the 2024 rows, then the 2025 rows: 5,553 + 3,475 = 9,028 rows, the same columns
  • df.merge(counts, on="region", …)attach each region’s project count to every project: same 34,079 rows, one more column
Binning

Converting a number into a countable category

Binning sorts numbers into ranges (bins). Sometimes the useful question is not "how many days" but "short, normal or delayed". pd.cut uses edges chosen by the analyst.

  • bins = [-9999, 0, 90, …]the edges: below 0, 0–89, 90–364 days…
  • right=Falseeach bin includes its left edge, not its right: 90 days counts as 3–12 months
  • .value_counts().sort_index()count per bin, in bin order rather than biggest first

cut vs qcut

cut uses edges chosen by the analyst, suitable when the boundaries have meaning. qcut makes equal-sized groups, suitable for quartiles.

bins = [-9999, 0, 90, 365, 730, 9999] labels = ["impossible", "<3mo", "3-12mo", "1-2yr", ">2yr"] print(pd.cut(df.duration, bins, labels=labels, right=False) .value_counts().sort_index()) duration impossible 1 <3mo 3049 3-12mo 21101 1-2yr 3080 >2yr 433 Name: count, dtype: int64
Binned result

The single-member bin is the main finding

under 0 days 1: contract 16DC0070, a data error under 3 months 3,049 (11.0%) 3 to 12 months 21,101 (76.3%) 1 to 2 years 3,080 (11.1%) over 2 years 433 (1.6%) 27,664 projects with both dates
Same scale

Comparing columns that are not in the same units

Budget is in pesos, duration in days, progress in percent. Any comparison of them (distance, clustering, a combined score) requires rescaling first.

Choice of method

Min-max when a fixed 0–1 range is required. Z-score when outliers matter and distance from the typical value is needed. On skewed money, z-score is safer.

x = df.budget minmax = (x - x.min()) / (x.max() - x.min()) z = (x - x.mean()) / x.std() print("min-max: largest", round(minmax.max(), 3), " median", round(minmax.median(), 3)) print("z-score: largest", round(z.max(), 1), " median", round(z.median(), 2)) min-max: largest 1.0 median 0.026 z-score: largest 28.8 median -0.19
  • x = df.budgetthe budget column, under a short name
  • (x - x.min()) / (x.max() - x.min())normalisation: smallest → 0, largest → 1
  • (x - x.mean()) / x.std()standardising (z-scores, week 5): how many standard deviations from the mean
Same scale, drawn

Min-max squeezes skewed budgets towards 0

min-max: every budget squeezed into 0 to 1 0 0.25 0.5 0.75 1 median 0.026 90th percentile 0.067 99th percentile 0.147 largest 1.000 z-score: standard deviations from the mean 0 5 10 15 20 25 30 median -0.2 90th percentile +1.0 99th percentile +3.4 largest +28.8 99% of budgets score below 0.15 on the min-max line; the largest is 28.8 standard deviations above the mean
Wide and long

Long and wide formats for the same numbers

Long is one row per observation, the format most plotting and grouping requires. Wide is one row per subject, the format readers prefer in a table.

Reshaping at the end

The analysis is done in long format, with a pivot to wide only for presentation. Wide tables are hard to filter and easy to break.

  • .reset_index()turn the group labels back into ordinary columns
  • long.pivot(index=…, columns=…, values=…)regions become rows, years become columns, budgets fill the cells
  • 18 empty cells18 regions × 11 years = 198 cells, but only 180 region-year pairs have projects
  • / 1e9 … round(2)show billions of pesos with two decimals
# long: one row per (region, year) long = (df.groupby(["region", "year"]) .budget.sum().reset_index()) print(long.shape) # wide: regions down, years across wide = long.pivot(index="region", columns="year", values="budget") print(wide.shape, "with", int(wide.isna().sum().sum()), "empty cells") print((wide.loc[["Region I", "Region III"], [2016, 2017]] / 1e9).round(2)) (180, 3) (18, 11) with 18 empty cells year 2016 2017 region Region I 5.08 5.90 Region III 8.00 9.97
Wide and long, drawn

Pivot and melt move the same numbers between two shapes

long: one row per region-year region year budget (B) Region I 2016 5.08 Region I 2017 5.90 Region III 2016 8.00 Region III 2017 9.97 .pivot() .melt() wide: regions down, years across region 2016 2017 Region I 5.08 5.90 Region III 8.00 9.97 The same four budgets (billions of pesos): 4 rows × 3 columns, or 2 rows × 3 columns
Exercise · 3 min

Aggregation changes the grain

Aggregation turns many values into one summary (a sum, a count, a mean). Grouping by region and summing turns city rows into one row per region: smaller and clearer, but the city detail is no longer in that frame.

Tasks

  1. Predict the Visayas total.
  2. Select ▶ Run / Edit and run the code.
  3. Change .sum() to .mean(). Which region is larger now?

Result on the lecture laptop (select to reveal)

Visayas 33 (24 + 9) and Mindanao 22. With .mean(): Visayas 16.5 and Mindanao 22.0. The summary chosen decides which region looks larger.

Grain = unit of analysis

“One row per city” and “one row per region” answer different questions. Each frame has one grain.

cities = pd.DataFrame({"city": ["Cebu", "Davao", "Iloilo"], "region": ["Visayas", "Mindanao", "Visayas"], "sales": [24, 22, 9]}) by_region = (cities .groupby("region")["sales"] .sum() .reset_index()) print(by_region)
  • .groupby("region")split the rows into piles, one per region
  • ["sales"].sum()add up the sales in each pile
  • .reset_index()make region an ordinary column again
Grain

Each aggregation answers a different question

Group byRows outQuestion answered
nothing34,079Cost of each individual project
region18Distribution of spending across the country
year11Change in spending over time
contractor4,841Contractors doing the work
Naming aggregates

One row per region, stated in the name

The output receives an explicit name. Many aggregation errors come from treating a summary table as if it were the original.

  • .agg(projects=("contract_id", "count"), …)several summaries at once; each is new name = (column, summary)
  • 18one row per region now: the grain changed
  • top.total / 1e9for display only: totals in billions and typical budgets in millions of pesos

Count as well as sum

A region with a large total from 12 projects differs from one with the same total across 900.

by_region = df.groupby("region").agg( projects=("contract_id", "count"), total=("budget", "sum"), typical=("budget", "median"), ) print(len(by_region)) top = by_region.sort_values("total", ascending=False).head(3) top["total"] = (top.total / 1e9).round(1) # billions of pesos top["typical"] = (top.typical / 1e6).round(1) # millions of pesos print(top) 18 projects total typical region Region III 5412 267.7 46.3 National Capital Region 3925 159.2 29.2 Region V 2814 155.6 46.8
Sampling

Reproducible sampling

Sampling means taking a random subset of rows. Sampling is for inspection, not for conclusions. The seed is what makes it reproducible.

Tasting a spoonful of stirred soup (random) from a recorded spoon (the seed), so that others can taste the same spoonful.

Without random_state it is not reproducible

The reported number could not be obtained again by anyone, including the original analyst.

print(df.sample(500, random_state=42).shape) # the same number from every region per_region = df.groupby("region").sample(n=50, random_state=42) print(per_region.shape) (500, 16) (900, 16)
  • random_state=42the seed: a fixed starting number for the random picks, so the same rows come back
  • .groupby("region").sample(n=50, …)50 random rows from each region’s pile: 18 × 50 = 900 (the smallest region has 180 projects)
Exercise · 8 min

Using a derived column to find an error

1 · Convert properly

Load the flood CSV. Convert budget with pd.to_numeric and both date columns with pd.to_datetime, all with errors="coerce".

2 · Count the failures

How many became NaN in each conversion? Does the number match the week 5 result on missing dates?

3 · Derive and check

Make duration. Run .describe(). Find the negative value.

4 · Make a second derived column

Try cost_per_day = budget / duration. What goes wrong, and which rows cause it?

Review question

Question (select to reveal the answer)

Joining 34,079 projects to a region table returns 68,158 rows. What is the most likely cause?

A · The join worked; merge always returns both tables’ rows
B · The region table has 2 rows per region, so every project matched twice
C · how="left" was used instead of how="inner"
D · pandas duplicated the rows to align the indexes
B. A repeated key on the right multiplies matching rows on the left. Every budget is now counted twice and every later total is doubled. Check with regions.region.duplicated().any() before joining, and compare len(df) before and after.
Review question

Question (select to reveal the answer)

Why did computing duration reveal an error that checking start_date and completion_date separately did not?

A · The date columns had invalid formats that only parsing reveals
B · The error is in the relationship between the columns, not in either value
C · Subtraction repairs corrupted dates
D · describe() checks more thoroughly than isna()
B. 2016-05-23 and 2016-05-06 are both perfectly valid dates. Only together do they say a project finished before it started. A derived column is a consistency test at no extra cost, which is why its range is checked as soon as it is created.
Exercise · 3 min

Sampling large data reproducibly

A million rows cannot be inspected directly. A random sample shows their general character, and random_state makes it the same sample on every run.

Tasks

  1. Predict whether the two printed lists match.
  2. Select ▶ Run / Edit and run the code.
  3. Delete random_state=0 from both lines and run twice. What happens?

Result on the lecture laptop (select to reveal)

Both lists are [993, 859, 298, 553, 672]. Without the seed the two lists differ from each other, and both change on every run (one laptop run gave [206, 954, 5, 569, 721] and [320, 2, 938, 33, 861]).

Reason for fixing the seed

Anyone who reruns the notebook sees the same rows, so claims about them can be checked.

rng = np.random.default_rng(6) budgets = pd.DataFrame({"budget": rng.integers(1, 100, 1000)}) # made-up a = budgets.sample(n=5, random_state=0) b = budgets.sample(n=5, random_state=0) print(a.index.tolist()) print(b.index.tolist())
  • rng.integers(1, 100, 1000)1,000 made-up budgets, in millions
  • .sample(n=5, random_state=0)5 random rows; the seed fixes which 5
  • .index.tolist()the row labels of the sample, as a list
Review question

Question (select to reveal the answer)

A frame was aggregated to one row per region and the city-level frame was deleted to save space. The question is then: "Which city drove the Visayas total?" Can it be answered?

A · Yes — divide the total by the number of cities
B · Yes — pandas remembers the original rows
C · No — aggregation is one-way; the detail is gone from that frame
D · Yes, if a sample was taken first

C: the sum removed the answer.

A total of 33 does not show that it was 24+9. Aggregation removes within-group detail, which is acceptable if the detailed frame still exists. The working copy is reduced; the fine-grained one is kept.

Overview

Weeks 3–6 as one pipeline

1

Acquire

Scraping or calling an API (weeks 3–4).

2

Clean

Gaps and outliers, treated deliberately (week 5).

3

Integrate & transform

Merging, harmonizing, deriving (this week).

4

Reduce

The frame that fits the question (this week).

Glossary

Terms introduced in Parts A–B

Combining tables

concatenate
stack tables end to end: pd.concat
index
the row labels down the left; ignore_index renumbers them
key
the shared column used to match rows
primary key
a key that names each row exactly once
merge / join
side by side by matching keys (VLOOKUP)
inner / left / outer join
matches only / every left row / everything
duplicate
a row identical to an earlier one
fan-out
a repeated key multiplying rows in a merge

Transforming values

data type
what a column holds: number, text, date
derived column
a column computed from other columns
assert
check a claim; stop with a message if it is False
harmonise labels
make spellings identical before grouping or joining
scaling
rescale columns to a comparable range
normalisation
min–max scaling to 0–1
standardising
z-scores: mean 0, standard deviation 1
encoding (one-hot)
one 0/1 column per category
Glossary

Terms introduced in Part C

Making it smaller

binning
numbers sorted into chosen ranges: pd.cut
aggregation
many values → one summary: sum, count, mean
grain
what one row stands for
long vs wide
one measurement per row vs a grid
pivot / melt
long → wide / wide → long

Fewer columns, fewer rows

dimensionality reduction
fewer columns, as little information lost as possible
dimension
one column (feature) of the data
sampling
a random subset of rows, for looking
random seed
fixed start for random picks: random_state=42
reproducible
anyone can rerun it and get the same result
This week's lab

Assembling, de-duplicating and reducing

Two months of sales to stack, a metadata table to join (note Davao's NaN), duplicates to drop without losing 2025, and a frame to reduce. About 45 minutes, in the portal’s lab page: fill each ____, press Run, then Check.

Lab tasks

pd.concat with ignore_index, pd.merge with how=, drop_duplicates and the subset= error, and column selection.

Optional extension

Aggregate cities into regions with groupby, and take a seeded sample, with an explanation of why the seed matters.

Summary

Four main points

Readings

Preparation for next week

Next week

Data exploration I

Descriptive statistics and univariate EDA: the analysis-ready table is used to answer questions, one variable at a time.

DS 227 · Knowledge Discovery in Data