Summarising by category, joining two tables on a shared key, and pivoting data between long and wide: the operations behind most analyses.
Programming for Data Science · University of the Philippines Cebu
Split by category, apply a summary, combine the results.
Join two tables that share a key into one.
Pivot between long, tidy data and wide, readable tables.
Week 6 selected rows. This week summarises, combines and reshapes them to answer questions.
All three have Excel equivalents. Part A is a PivotTable's "sum by region", Part B is VLOOKUP (fetch a value from another sheet by matching a name), and Part C is turning a long list into a grid and back.
Compute the average per region in a single line.
In plain words: grouping sorts the rows into piles by a key column, computes one summary per pile, and stacks the summaries into a small table with one row per pile.
rg = f( { xi : ki = g } ) for every distinct key value g
| Part | For the eight cities |
|---|---|
| ki, the key | the region of city i: Luzon, Mindanao or Visayas |
| xi, the value | the population of city i |
| Gg, a group | the rows with ki = g: GLuzon = Quezon City, Manila, Baguio |
| f, the summary | the mean |
| rg, one result row | rLuzon = (2,960,000 + 1,847,000 + 366,000) ÷ 3 = 1,724,333 |
| In pandas | cities.groupby("region")["pop"].mean() |
Wickham, H. (2011). The split-apply-combine strategy for data analysis. Journal of Statistical Software 40(1).
Sort the rows into piles, one pile per distinct value of a column.
e.g. df.groupby("region") makes one pile per region
A summary that turns many values into one: mean, sum, count, max.
e.g. .agg(["mean", "count"])
Split into groups, summarise each group, stack the answers into one small table.
e.g. 34,079 project rows → 18 region rows
The column two tables share, used to decide which rows belong together.
e.g. city in both the population and the area table
Combine two tables side by side by matching their key values, like Excel's VLOOKUP.
e.g. pd.merge(pops, areas, on="city")
Which rows survive a merge: only matches, every row of the left table, or everything.
e.g. how="left"
Stack tables under (or beside) each other, without matching any key.
e.g. pd.concat([january, february])
Long: one measurement per row. Wide: a grid, with one category spread across the columns.
e.g. city, year, sales vs city, 2024, 2025
Turn long into wide; pivot_table also summarises repeats, like an Excel PivotTable.
e.g. pivot_table(index="region", columns="year", …)
Turn wide back into long: every cell of the grid becomes its own row.
e.g. wide.melt(id_vars="city")
Filtering can keep the Visayan cities, but "the average population of each region" requires a summary per category. Grouping provides this.
cities: a tiny table (city, region, pop) small enough to
check every row by eye. projects: the 34,079 flood-control projects from
week 6 (contract_id, region, year, budget, status). Both are called
df in the code; the column names identify which one it is.
Filtering gives one subset. Grouping gives every subset at once.
Many questions require two tables joined on a shared column.
Databases have long grouped rows before summarising them.
Hadley Wickham calls it split-apply-combine and builds an R package around it.
Its user guide is titled “Group by: split-apply-combine”.
Wickham’s summary: break a big problem into pieces, work on each piece independently, then put the pieces back together.
Once the three steps are familiar, the same idea can be recognised in any data tool, whatever the function is called.
SourceH. Wickham, “The Split-Apply-Combine Strategy for Data Analysis,” J. Statistical Software 40(1), 2011; pandas user guide: Group by
SELECT region, AVG(cost) FROM projects GROUP BY region
projects |> group_by(region) |> summarise(mean(cost))
projects.groupby("region")["cost"].mean()
All three split the rows by region, take the mean of each group and combine the means into one small table.
Sourcepandas user guide: Group by; dplyr reference: group_by
As in weeks 5 and 6, a block with a ▶ Run / Edit button runs in the browser and can be changed and run again. The first run downloads Python and pandas, which takes 10 to 20 seconds.
Printed outputs on the slides come from the lecture laptop, which runs pandas 3. The browser runs pandas 2.2, so text columns print as object instead of str. Blocks that download the flood data have no button; the notebook runs those.
pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browsert.dtypeseach column’s type: str on the laptop and object in the browserSplit, apply a summary, combine.
Week 6 computed one summary of a whole column, such as df["pop"].mean(). This part computes the same summary once per category, in one line.
The rows i = 1…n split into groups Gg = { i : ki = g }, one per distinct key g. Every row lands in exactly one group, so the group sizes add up to n. Three kinds of apply follow:
aggregate: one value f(Gg) per group · transform: row i gets f(Gki), so n rows come back · filter: keep all of Gg or none of it, by a test on the group
| Part | Applied to the eight cities |
|---|---|
| groups | Luzon 3, Mindanao 2, Visayas 3: 3 + 2 + 3 = 8 rows |
| aggregate | 3 rows, one mean per region |
| transform | 8 rows; Cebu gets the Visayas mean, 557,333 |
| filter: mean > 1,000,000 | 5 rows; all three Visayas cities go, because 557,333 < 1,000,000 |
Wickham (2011), as above; McKinney, W. (2022). Python for Data Analysis, 3rd ed., ch. 10.
Group the rows by a category, apply a summary to each group, then combine those summaries into a small result table. The same pattern recurs throughout data analysis.
To group by a column means to
sort the rows into piles, one pile per distinct value (every "Visayas" row in one pile). An
aggregation is a summary that turns many values into one —
mean, sum, count, max.
Receipts are sorted into one pile per store (split), each pile is added up (apply), and the totals are written on one sheet (combine).
Rows fall into buckets by region.
Each bucket gets a summary — mean, sum, count.
One row per group, stacked into the answer.
Parts A to C use one small table typed on the slide: eight cities, the island group each belongs to, and an approximate 2020 census population. Week 6’s five cities are among them.
csv_text = """…"""the table as CSV text: a header line, then one city per linepd.read_csv(io.StringIO(csv_text))read the text as if it were a file, as in week 6regionhere the island group (Luzon, Visayas, Mindanao), not the flood data’s administrative regionThe group column becomes the index of the result. There is one row per distinct value, regardless of the number of input rows.
This is NumPy's axis idea again (week 5: the direction of summarising): collapse many values to one, per group.
groupby followed by a summaryThe code names the column to group on, the column to summarise, and the summary. pandas returns one value per group, indexed by the group name.
A PivotTable with "region" in Rows and "Average of pop" in Values, written as one re-runnable line.
cities.groupby("region")split the cities table into one pile per region["pop"]in each pile, look only at the population column.mean().round()average each pile’s populations, rounded to whole peopleLuzon 1724333.0a Series: the region names are its index (row labels); Luzon’s three cities average 1,724,333 people.agg() for a per-group reportA list of summaries gives one column for each. .agg() is short for aggregate: “apply these summaries”. It takes one name ("mean") or a list of names in square brackets.
"max" to "median". For which region are the mean and the median equal, and why?Result on the lecture laptop (select to reveal)
Luzon and Visayas have 3 cities each, Mindanao 2; Luzon has the largest city (2,960,000: Quezon City). With "median", Mindanao’s mean and median are both 1,252,500: with two cities, the median is the average of the two.
.agg(["mean", "max", "count"])run three summaries on every pile; each one becomes a column.round()round the means to whole people for displayThe rest of Part A applies the same grouping to real data: the 34,079 flood control projects from weeks 5 and 6, 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 the flood blocks have no Run button; the companion notebook runs them.
requests.get(url)download the whole table in one request, as in weeks 5 and 6pd.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 tableEach function name in the list is computed per group. This table is a useful first check after any grouping.
A mean over 12 projects is far less reliable than a mean over 5,412, and only the count shows which applies.
.agg(["count", …, "max"])seven summaries of budget per region; each becomes a columnstats.shape(18, 7): 18 regions, 7 statisticstop.index[:3]the three regions with the largest median projectThe same three steps apply to a real table. The output has one row per region, because the grain changed — grain means "what one row stands for". Before: one project per row. After: one region per row.
Named aggregation means writing new_name=(column, summary), which sets the output column names. Without it the result can have a MultiIndex: two-level column labels such as ("budget", "sum") that are awkward to use.
.agg(projects=("contract_id", "count"), …)several summaries at once; each is new name = (column, summary)34079 projects -> 18 regionsthe grain changed: one row per region nowRegion III receives the most money. Central Office runs the biggest projects — 180 of them, each typically three times a Region III project. The choice of summary determines the conclusion.
"Total spend" shows where most of the money went; the median (the middle value once the projects are sorted by size) shows the size of a typical project there. The two measures answer different questions.
A list of column names gives one row per combination that exists — not per possible combination.
18 regions × 11 years is 198. Eighteen of those pairs never occurred, and groupby does not create them.
groupby(["region", "year"])one pile per region-and-year pair.budget.sum().reset_index()total budget per pile, with the keys back as ordinary columns180 vs 19818 regions × 11 years would be 198 pairs; 18 pairs have no projectsBy default the group key becomes the index (the row labels), which is inconvenient for merging or plotting. One argument avoids the reset_index() that usually follows.
reset_index() moves the row labels back into an ordinary column and numbers the rows 0, 1, 2… again.
The result is the same. Either form may be used for readability, but the choice matters because .loc behaves differently.
type(s).__name__the name of the result’s type: a Series or a DataFrameas_index=Falsekeep region as an ordinary column instead of the indexAggregation without collapsing, so that every row can be compared with its own group.
groupby with a summary gives one row per group. transform computes the same per-group summary but copies it back onto every original row.
agg gives one row per group. transform gives one row per original row, filled with that row’s group value.
Judging whether a project is large for its region requires the region median next to every project.
.median()one value per region: 3 rows.transform("median")the same medians, written onto every city’s row: 8 rows, in the table’s orderAgg writes one line per class on a report; transform writes the class average next to each student's own mark.
Two lines convert an absolute number into a relative one, which is usually the more informative measure.
₱279.8M in Region V, where the median is ₱46.8M. That is 5.98× a typical project there , which no single-column summary could show.
df["reg_median"] = …each project gets its own region’s median budgetdf.budget / df.reg_medianhow many times its region’s typical project this one costsvs_region 5.98the first project costs about six times its region’s median17,036
projects
17,036
projects
A median splits each group in half (the other 7 projects sit exactly on their region’s median). Any other result would indicate a misaligned transform.
This provides a correctness test at no cost. transform aligns results back to the original index (it puts each value on the row with the same row label); if it had not, the split would not be even. Guideline: check the shape (rows and columns) and a known property after every use.
Different from a boolean mask (week 6: a True/False per row that picks rows): here the test runs per group, and either the whole group stays or the whole group goes.
A lambda is a tiny function written in one line, with no name. lambda g: len(g) > 3000 means "given a group g, answer True if it has more than 3,000 rows".
Comparing regions with 12 projects against ones with 5,000 is rarely fair; this drops the small groups in one line.
.filter(lambda g: len(g) > 3000)keep every row of a region whose pile has more than 3,000 projects4 162914 regions pass, with 16,291 projects between themAnother transform-shaped tool: it returns one value per row, giving each project’s position in its own region.
Two projects at the same budget both get the lower rank, which matches the usual meaning of "joint first".
A class ranking per section, where a student is "3rd in the section" rather than "412th in the school".
.rank(ascending=False, method="min")1 = the largest budget within its regiondf[df.rank_in_region == 1]the largest project of each region: 18 rows/ 1e6show the budgets in millions of pesosSort descending (biggest first), take a running total, divide by the sum. The result shows how few projects account for half the money.
A running total (cumsum, "cumulative sum") adds each value to everything above it: 5, 3, 2 becomes 5, 8, 10.
Its top 1,357 projects — 25.1% of them — account for 50% of its ₱267.7B. This is concentrated, but not extreme.
r3.budget.cumsum() / r3.budget.sum()running total of the budget, as a share of the region’s whole budget(r3.cum_share <= .5).sum() + 1how many projects, largest first, it takes to reach halfIf every project cost the same, the curve would follow the dashed line. It rises steeply instead: the largest projects take most of the money, and the curve passes 50% after only 1,357 of 5,412 projects.
The further the curve sits above the dashed line, the more concentrated the spending.
What does
df.groupby("region")["pop"].sum() return?
B — one total per region.
Grouping produces one summary row per distinct
group value, indexed by that value. A plain df["pop"].sum() would give
the single grand total (A).
Group first → per-group answers. No group → one grand total.
One result row per group value.
Build by_region with projects, total and median. Confirm it has 18 rows.
Which region leads on total? Which leads on median? Explain in one sentence why they differ.
Use transform to add vs_region. Find the project with the highest ratio , the largest project relative to its region.
Count how many rows are above vs below their region median. An uneven split indicates a misaligned transform.
Step 3 is the deliverable: an absolute number ranks the biggest projects; a relative one identifies unusual ones.
Which tool compares each project with its own region’s median budget?
groupby(...).agg("median") — then merge it backgroupby(...).transform("median") — it returns one value per original rowgroupby(...).filter(...)pivot_table with aggfunc="median"transform returns a result aligned to the original index — 34,079 values for 34,079 rows — so it fits directly into a new column. A works but takes an extra merge and a chance to misalign; C keeps or drops whole groups; D changes the grain entirely.Two tables, one shared key, joined into one.
Part A used one table. This part adds columns from a second table by matching rows on a shared column, the code equivalent of Excel's VLOOKUP.
L ⋈ R = { (l, r) : l ∈ L, r ∈ R, key(l) = key(r) }
That is the inner join. A left join also keeps every row of L with no partner, filling R’s columns with NaN; an outer join keeps the unmatched rows of both sides.
| Part | pops ⋈ areas, on city |
|---|---|
| keys | pops: Cebu, Iloilo, Davao · areas: Cebu, Iloilo, Manila |
| inner: keys in both | Cebu, Iloilo → 2 rows |
| left: every pops key | + Davao, area NaN → 3 rows |
| outer: keys in either | + Manila, pop NaN → 4 rows |
| rows for one key | nL(k) × nR(k): Cebu twice in each table gives 2 × 2 = 4 rows |
The circles hold key values, not rows, so they cannot show the last line: a repeated key multiplies rows. validate=, later in this part, catches it.
Codd, E. F. (1970). A relational model of data for large shared data banks. Communications of the ACM 13(6).
Population sits in one file, land area in another. Both have a
city column — the key. Merging aligns them so that density can be computed.
city)Excel's VLOOKUP finds each city from sheet 1 in sheet 2 and copies its area across. merge does that for every row and every
column at once.
city, region, pop
city, area_km2
city, matched row by row.
merge on the shared columnon= names the key. pandas matches rows where the key agrees and joins the columns into one wider table, so population and land area sit in the same row.
ascending=False to ascending=True. Which cities are least dense, and why?Result on the lecture laptop (select to reveal)
Manila: 43,976 people per km², more than twice Quezon City’s 17,209. With ascending=True the least dense come first: Davao (727 per km²), Tacloban (1,243) and Cagayan de Oro (1,763). Davao covers 2,444 km², so its people are spread thin.
SourceLand areas from each city’s Wikipedia article, rounded to whole km²; populations are approximate 2020 census figures.
pd.merge(cities, areas, on="city")for each city, find the row of areas with the same city and glue its columns onboth["density"] = …population and area now sit in the same row, so dividing gives people per km²how=how= | Keeps | Use when |
|---|---|---|
"inner" (default) | keys in both | only complete matches are needed |
"left" | all of the left table | enrich a main table, keep every row |
"right" | all of the right table | same idea, other side |
"outer" | keys in either | unmatched rows must be visible |
The join type (how=) decides what happens to rows
whose key appears in only one table. Unmatched rows fill with NaN. An unexpected NaN after a merge almost always indicates a key that did not match.
inner silently drops non-matches, so the row count should be checked afterwards.
innerkeeps only cities found in both tables; Davao and Manila are dropped without warningleftkeeps every row of pops; Davao has no area to look up, so it gets NaNouterkeeps every city from either table; each gap is NaNA left join is VLOOKUP applied down the main sheet; every row stays, and a failed lookup leaves a blank (NaN). Note that 315 became
315.0: a number column that holds a NaN is stored as decimals (float).
The most harmful merge error runs without failing: a duplicated key silently doubles the rows, and every later total is wrong. One argument prevents it.
many_to_one, one_to_one, one_to_many. If the data disagree, pandas raises an error instead of guessing.
many_to_one means "many project rows may share a region, but the lookup table regions lists each region only once". To raise means to stop with an error message (an exception, week 4).
validate="many_to_one"state the expected relationship: many cities, one area row eachpd.concat([areas, areas.head(1)])a copy of areas with Quezon City listed twiceMergeErrorthe merge refuses to run, so the doubled row never reaches a totalindicator=True labels every rowindicator=True adds a column, _merge, saying where each row found its partner: both, left_only or right_only. Counting it is the quickest check after a merge.
left_only.!= "Davao" to == "Davao", keeping only Davao’s area. How many are left_only now?Result on the lecture laptop (select to reveal)
1 city, Davao, is left_only; the other 7 are both. Keeping only Davao’s area reverses it: 7 cities are left_only and only Davao is both.
areas[areas.city != "Davao"]a copy of areas without Davao, to make one key failm["_merge"].value_counts()how many rows matched on each sidepd.concat joins tables without a key. With axis=0 (the default) it stacks rows and expects the same column names. With axis=1 it places tables side by side and matches rows by their index labels, not by position.
The second result has 6 rows, not 3: the labels 0–2 and 5–7 never match, so every cell from the other table is NaN. No warning is raised.
pd.concat([cities.head(2), cities.tail(1)])the first two rows, then the last one; each keeps its old labelpd.concat([left, right], axis=1)side by side, lined up by label: 0, 1, 2 and 5, 6, 7 share nothingA merge expected to be many-to-one returns 68,158 rows from a 34,079-row left frame. What would have caught this at the moment it happened?
how="inner" instead of how="left"validate="many_to_one", which raises MergeError on a duplicated right keyvalidate= checks the expected relationship and raises immediately; indicator=True then shows which rows matched. Without them, the first symptom is a total that is exactly double, three steps downstream.Next: reshaping tables.
Long for analysis; wide for reading.
Parts A and B summarised and combined tables. This part changes their layout (the same numbers as a long list or as a grid) without changing any value.
A long table holds one row (r, c, v) per measurement. A wide table puts the same values in a grid: W[r, c] = v.
pivot needs each (r, c) pair at most once; pivot_table allows repeats and stores W[r, c] = f( { v : rows with that r and c } ). melt reverses it: every cell W[r, c] becomes the row (r, c, W[r, c]).
| Part | For the four sales numbers |
|---|---|
r → index= | region: Luzon, Visayas |
c → columns= | year: 2024, 2025 |
v → values= | sales |
| long ↔ wide | 4 rows ↔ 2 rows × 2 year columns; W[Luzon, 2025] = 25 |
| melt of the grid | 2 × 2 = 4 rows again |
Wickham, H. (2014). Tidy data. Journal of Statistical Software 59(10). Long form is his “tidy” layout: one variable per column, one observation per row.
Long form has one measurement per row — ideal for grouping and plotting. Wide form spreads a category across columns — ideal for a human to scan.
A long table is a receipt roll with one line per sale; a wide table is a grid with cities down the side and years across the top.
city, year, sales — one number per row.
city, 2023, 2024, 2025 — years as columns.
sales.pivot_table(index="region", columns="year", values="sales", aggfunc="sum")regions become rows, years become columns, sales fill the cellswide.reset_index().melt(id_vars="region", var_name="year", value_name="sales")back to four rows: one per cell of the gridNo values are added or lost: both tables hold the same four numbers. Long is easier for code (group it, plot it); wide is easier for eyes (compare 2024 with 2025 across a row). pandas sorts the regions alphabetically, so Luzon comes first.
pivot_table spreads a category outThe values of one column become new column headers: each year gets its own column, and each region its own row.
Result on the lecture laptop (select to reveal)
2 rows (Luzon, Visayas) by 2 year columns. With the extra row, Luzon 2025 shows 30: aggfunc="sum" adds the two Luzon 2025 rows, 25 + 5. Plain pivot would raise an error on the repeated pair.
index="region"one row per regioncolumns="year"one column per yearvalues="sales", aggfunc="sum"fill each cell with the sales, added up if a region-year appears twicepivot fails if a cell would hold more than one value. pivot_table takes an aggfunc (the aggregation to use) and summarises instead.
Without it, combinations that never occurred show as NaN — which is accurate but harder to read in a count table.
aggfunc="count"count the projects in each region-status cell instead of adding budgetsfill_value=0write 0, not NaN, where a region has no project of that status(18, 5)18 regions by 5 statuses; two of each are printedmelt folds columns into rowsmelt is the reverse of a pivot. It keeps an id column and gathers the rest into a name/value pair, the tidy shape most tools and plots expect.
To melt a table is to turn wide into long: each cell of the grid becomes its own row, labelled with the column heading it came from.
wide.reset_index()make region an ordinary column againid_vars="region"the column to keep as it isvar_name="year", value_name="sales"names for the two new columns: the old headers and the old cellsMost plotting libraries want long form: one row per observation, with the variable name in a column. melt is the inverse of pivot.
Everything not named there gets folded into the variable/value pair.
df.pivot_table(…)total budget per region and year: 18 rows × 11 year columns.melt(…)one row per cell: 18 × 11 = 198 rows, including the 18 empty onesA shortcut for the count-only pivot: given two columns, it counts every combination. crosstab is short for "cross-tabulation" — a table of counts with one category down the side and another across the top.
normalize="index" makes each row sum to 1, so regions of very different sizes can be compared fairly.
pd.crosstab(df.region, df.status)count the projects for every region-status pair: 18 × 5normalize="index"divide each row by its total, so each region’s shares add up to 10.81781.7% of Region III’s projects are completed| Task | Use | Rows out |
|---|---|---|
| One summary per group | groupby().agg() | one per group (18) |
| Each row vs its group | groupby().transform() | same as input (34,079) |
| Position within group | groupby().rank() | same as input (34,079) |
| Keep or drop whole groups | groupby().filter() | a subset of input |
| Counts of two categories | pd.crosstab() | a grid (18×5) |
The deciding question is whether the result needs one row per group or one row per original row. That distinction identifies the right tool in almost every case.
One question that needs all three parts: merge two tables, derive a column, then group. Each step is one line.
.max() to .mean(). Does the order of the regions change?Result on the lecture laptop (select to reveal)
Luzon (Manila, 43,976 people per km²), then Visayas (Iloilo, 5,859) and Mindanao (Cagayan de Oro, 1,763). With .mean(): Luzon 22,499, Visayas 3,387 and Mindanao 1,245, the same order.
cities.merge(areas, on="city")merge (Part B): population and area in one tableboth["density"] = …a derived column (week 6): people per km².groupby("region")["density"].max()group (Part A): the highest density in each regionA merge must keep every row of the left table, matched or not. Which how=?
"inner""left""right""outer"B — "left".
A left join keeps all left rows, filling
unmatched right columns with NaN. "inner" would drop the rows that did not match.
The join type follows from which table must keep all its rows.
Left join keeps the left; inner keeps only matches.
The lab summarises a dataset by category, joins it to a second table on a key, and pivots the result between long and wide to answer set questions. ~45 minutes.
groupby.agg, merge(on=, how=), pivot_table, and
melt.
Group by two columns at once: groupby(["region", "year"]).
Split by category, apply a summary, combine: one row per group.
Join on a shared key; choose how= by the rows to keep.
pivot_table long→wide; melt wide→long.
In summary: summarise by group, join in missing information, and reshape to suit the question or the reader.
Combine several raw tables into one clear, summarised result.
new_name=(column, summary) inside .agg(): sets the output column nameslambda g: len(g) > 3000pivot_table also summarises repeats (Excel PivotTable)Finish the Week 7 lab and submit it. A groupby.agg should be possible from memory.
pandas "Group by: split-apply-combine" —
pandas.pydata.org/docs/user_guide/groupby.
Everything here is linked on the course page beside this deck.
Converting these tables into charts that are quick to read.
Turning a summarised table into a chart that shows the pattern clearly, and the small set of plot types used most often.
DS 208 · Programming for Data Science