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
Stacking, joining and de-duplicating combine information from several tables into one frame.
Correcting types, harmonizing labels and deriving the columns the question requires.
Fewer columns and fewer rows, retaining what the question needs.
Last week addressed errors inside one table. This week's problems arise with more than one table, as in every real project.
As in week 5, every merge, rename and drop is a decision that others should be able to audit.
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.
Different systems, owners and months. No source provides the analysis table; the analyst builds it.
Joins that drop rows without warning, duplicates that double totals, and labels that almost match. None of these raises an error.
Edgar F. Codd at IBM proposes keeping data in tables linked by shared keys.
IBM researchers design a language to query those tables; it becomes SQL.
One of the first commercial SQL databases goes on sale.
Codd is honoured for his contributions to database theory and practice.
IBM was slow to adopt the idea because it already sold a different kind of database; competitors shipped first.
pandas’ merge is Codd’s join: rows from two tables are matched wherever a key column agrees.
The four most popular database systems are all relational: Oracle, MySQL, SQL Server, PostgreSQL.
Six of the ten most popular database systems are relational.
Inner, left, right and outer joins mean the same in SQL and in pandas.
Fifty-six years later, a table plus a join is still the default way to store and combine data.
SourceDB-Engines ranking, October 2026; pandas: Merge, join, concatenate
Join tables end to end: the rows of one go under the rows of the other.
e.g. pd.concat([jan, feb])
The column two tables share, used to decide which rows belong together.
e.g. city, or a project’s contract_id
Put two tables side by side by matching their key values, like Excel’s VLOOKUP.
e.g. pd.merge(sales, meta, on="city")
Which rows survive a merge: only matches; every row of the left table; everything.
e.g. how="left"
A new column computed from existing ones.
e.g. duration = completion date − start date
Rescaling columns so that columns with large numbers do not dominate those with small numbers.
e.g. pesos in millions next to percent
The min–max kind of scaling: smallest value → 0, largest → 1.
e.g. (x - x.min()) / (x.max() - x.min())
Turning a text category into numbers: one 0/1 column per category.
e.g. status_Completed = 1 or 0
Sorting numbers into ranges (bins) so that they can be counted as categories.
e.g. duration → “<3mo”, “3-12mo”…
A summary that turns many values into one: sum, count, mean.
e.g. one total per region
What one row stands for: a project, a region, a region-year.
e.g. 34,079 project rows vs 18 region rows
Long: one measurement per row. Wide: a grid with one category across the columns.
e.g. region-year rows vs a years-across table
Keeping fewer columns while losing as little information as possible.
e.g. dropping a column that is 0 on every row
Taking a random subset of rows to look at.
e.g. df.sample(500, random_state=42)
A fixed starting number for random picks, so the same “random” rows come back every time.
e.g. random_state=42
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.
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.
strpd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browsersys.maxsize > 2**32True on the laptop’s 64-bit Python, False in the browser’s 32-bit onet.dtypeseach column’s type: str on the laptop, object in the browserTwo 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.
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.
ignore_index=TrueWithout 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, febtwo small tables with the same two columns, city and sales[jan, feb]a list of the tables to stack, in order: January firstignore_index=Truenumber the rows afresh, 0 to 3 (the row labels are the index)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.
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.
pd.merge(sales, meta, …)the left table first, then the right tableon="city"the key: match rows whose city is the samehow="left"keep every row of the left table, matched or nothow= parameter
left keeps every main row and marks gaps with NaN; inner deletes the non-matches without warning; outer keeps everything from both tables. The choice depends on whether losing rows is acceptable.
Print len() before and after every merge. An unexplained change in row count indicates a problem in the data.
The choice is not stylistic. It determines which rows remain, and therefore which population the conclusion describes.
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 warningindicator=Trueadds a column _merge saying where each row matched: both or left_onlym[m._merge == "left_only"]the rows that found no partnerA 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.
Print len() before and after every join. An unexpected increase means totals are double-counted and every later percentage is wrong.
dup.city.is_uniqueFalse: some city appears more than once, so city is not a safe key3 rows -> 4 rowsone extra row from the second Cebu matchWhen 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.)
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.
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.
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.
requests.get(url)download the whole table in one request: export.csv is the bulk endpoint used in week 5pd.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 tableA 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.
34,079 ids for 34,079 rows. This is a valid primary key; it should be confirmed, not assumed.
.nunique()how many different values the column holds34079 34079as many different ids as rows: no id repeatsduplicated(keep=False)mark every copy of a repeated id, not only the second one; (0, 15) means noneA left join of 100 sales rows to a city table returns 130 rows. What happened?
ignore_index was forgottenB: 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.
In practice, a failed merge rarely raises an error; it produces a plausible but wrong table.
Before joining, check whether the key is unique in each table, in one line:
df["city"].is_unique.
Next: making the values usable.
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.
Scraped and merged data often arrives as strings: "31", "1,204", "2024-01-05". Types are corrected before any arithmetic.
"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.
pd.to_numeric(…, errors="coerce")text → numbers; anything unreadable becomes NaN instead of an errorpd.to_datetime(…)text like "2024-01-05" → real dates that can be subtracted and sortedWhen 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.
Sorting text puts ₱9M above ₱80M, because "9" > "8". A "top projects" list would be wrong, and no error would be raised.
rowsthe text read by csv.DictReader: a list with one dictionary (column name → value) per linerepr(…)print a value with its quote marks: '279839557.31' is text (a str), not a numbersorted([…])puts values in order; text is ordered character by character, like words in a dictionaryForcing 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.
If isna().sum() increases after a conversion, those rows held non-numeric values and should be inspected.
df["budget"] = …replace the column with its converted version.isna().sum()count the NaNs after converting: new ones are values that failed to convert973, 6414dates already blank in the file: 973 projects have no start date and 6,414 no completion dateduration = completion_date − start_date
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.
The rest are missing one of the two dates, which, as shown last week, means they are unfinished.
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 dayscount 27664.0only rows with both dates get a duration; the rest are NaNThe 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.
Such a row is practically impossible to find by eye. The derived column revealed it as soon as .describe() was called.
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 line00:00:00 / -17.0dates carry a time of day (midnight); the duration is a decimal because the column also holds NaN2016-05-23 is a real date, correctly formatted, inside the dataset’s range. Nothing to flag.
2016-05-06 is equally valid. Any per-column check passes it.
The error exists only between the columns. It is invisible until a quantity using both is computed.
This is the argument for deriving early: a derived column is a consistency test at no extra cost. Its range (min, max, and the number of impossible values) is checked as soon as it is created.
The check belongs in the same cell as the calculation, where the meaning of "impossible" for that quantity is still clear.
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 messageAssertionError: 1 negative durationsread the last line of the error: the type (a failed assert) and the messageTo a reader, one place. To merge and groupby, separate keys. Labels are harmonized before integration.
.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 → newA groupby treats "Cebu" and "cebu " as two different places. The flood data is clean, but this is known only because it was checked.
No case variants, no stray whitespace. This one-line check applies to any column used for grouping.
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.
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.
Raw totals mostly measure city size. Dividing by population gives a fair comparison, which can reorder the ranking.
cities["sales"] / cities["population"] * 100_000sales per 100,000 people: a rate, comparable across city sizescities["region"] == "Visayas"a flag: True or False on every rowPesos 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”.
Normalisation rescales each column to 0–1: (x − min) / (max − min). It is simple and bounded but sensitive to outliers.
Center at 0, spread of 1: (x − mean) / std. It measures how unusual a value is within its own column.
Whenever columns are combined or compared across units. Clustering and modeling in later DS courses depend on it.
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.
Numbering would make “On-Going” (2) count as twice “Completed” (1), implying an order and a distance that the categories do not have.
pd.get_dummies(…)pandas’ one-hot encoder (“dummy” columns is another name)columns=["status"]encode this column; city is left alonedtype=intwrite 1 and 0 instead of True and FalseNot 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.
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[["city", "region", "sales"]]a list of the columns to keep; internal_id and notes are left outDropping from the working frame is reversible because of week 5's rule: the raw file still has everything. Copies are reduced, never sources.
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.
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.
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.
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.
df.nunique()for every column, how many different values it holds.sort_values().head(4)the four columns with the fewest different valuesamount_paid 1one value everywhere: no informationdf.drop(columns=[…])a new table without that column; the raw file keeps itBoth "combine two tables". They change the shape in opposite ways, and the row count shows which one was applied.
After a concat, rows should be the sum of the inputs. After a merge, columns should be the sum minus the shared key.
pd.concat([y2024, y2025])the 2024 rows, then the 2025 rows: 5,553 + 3,475 = 9,028 rows, the same columnsdf.merge(counts, on="region", …)attach each region’s project count to every project: same 34,079 rows, one more columnBinning 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 firstcut uses edges chosen by the analyst, suitable when the boundaries have meaning. qcut makes equal-sized groups, suitable for quartiles.
Binning served two purposes: it made the distribution readable, and it isolated the impossible row in its own bin.
Budget is in pesos, duration in days, progress in percent. Any comparison of them (distance, clustering, a combined score) requires rescaling first.
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.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 meanOne budget of ₱1.45 billion fixes the top of the min-max scale, so the median project lands at 0.026. The z-score keeps the spread visible and reports the largest budget as an extreme value.
Use the z-score, or rescale after taking logs. Min-max suits columns without extreme values.
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.
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 columnslong.pivot(index=…, columns=…, values=…)regions become rows, years become columns, budgets fill the cells18 empty cells18 regions × 11 years = 198 cells, but only 180 region-year pairs have projects/ 1e9 … round(2)show billions of pesos with two decimalsLong format has one row per observation: here, one region in one year. Wide format spreads one variable (year) across the columns. .pivot() goes from long to wide; .melt() goes back.
Analyse in long format; pivot to wide only for a table a reader will see.
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.
.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.
“One row per city” and “one row per region” answer different questions. Each frame has one grain.
.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| Group by | Rows out | Question answered |
|---|---|---|
| nothing | 34,079 | Cost of each individual project |
| region | 18 | Distribution of spending across the country |
| year | 11 | Change in spending over time |
| contractor | 4,841 | Contractors doing the work |
Aggregation does more than make the data smaller: it changes what one row means. After a groupby, a row is no longer a project, so statements about "the average project" do not apply to it.
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 changedtop.total / 1e9for display only: totals in billions and typical budgets in millions of pesosA region with a large total from 12 projects differs from one with the same total across 900.
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.
The reported number could not be obtained again by anyone, including the original analyst.
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)Load the flood CSV. Convert budget with pd.to_numeric and both date columns with pd.to_datetime, all with errors="coerce".
How many became NaN in each conversion? Does the number match the week 5 result on missing dates?
Make duration. Run .describe(). Find the negative value.
Try cost_per_day = budget / duration. What goes wrong, and which rows cause it?
Note on step 4: dividing by a duration of 0 gives inf (infinity), not an error. Count them.
Joining 34,079 projects to a region table returns 68,158 rows. What is the most likely cause?
regions.region.duplicated().any() before joining, and compare len(df) before and after.Why did computing duration reveal an error that checking start_date and completion_date separately did not?
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.
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]).
Anyone who reruns the notebook sees the same rows, so claims about them can be checked.
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 listA 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?
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.
As with dropping columns, reduction discards information, so it is applied only to copies.
Name frames by their grain: sales_by_city, sales_by_region.
The name states the grain.
Scraping or calling an API (weeks 3–4).
Gaps and outliers, treated deliberately (week 5).
Merging, harmonizing, deriving (this week).
The frame that fits the question (this week).
This completes CRISP-DM's (week 2) Data Preparation phase. Its output is the analysis-ready table: one grain, verified values, and only the columns that are needed.
Exploration: over the next two weeks, the table is used to answer questions.
pd.concatignore_index renumbers thempd.cutrandom_state=42Two 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.
pd.concat with ignore_index, pd.merge with
how=, drop_duplicates and the subset= error,
and column selection.
Aggregate cities into regions with groupby, and take a seeded
sample, with an explanation of why the seed matters.
concat for same-shaped rows; merge on a key for new
columns; every NaN it produces is examined.
An unexplained change in row count indicates corrupted data.
Correct types, harmonized labels and derived rates, so that the table matches the question.
Aggregation and column-dropping cannot be undone within a frame; this is acceptable when the detailed frame is kept.
In summary: the goal is one verified table at the right grain, with a record of how it was built.
Data Preparation is complete. Exploration begins next week.
pandas User Guide, "Merge, join, concatenate and compare": its diagrams illustrate how=. pandas.pydata.org
Hadley Wickham's "Tidy Data" paper, sections 1–3: a clear argument for one-observation-per-row tables.
Both are linked on the course page beside this deck and the lab.
The merge diagrams are easier to follow after Davao's NaN has been seen in the lab.
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