5.4.21 · D3Scientific Computing (Python)

Worked examples — Pandas — Series, DataFrame, indexing, groupby, merge, pivot

4,694 words21 min readBack to topic

The scenario matrix

Every operation in pandas has a small number of "edge conditions" that change the output. Below is the full grid. Each cell is a scenario class; the worked examples that follow are tagged with the cell they cover.

Case class The tricky sub-cases Example that covers it
Alignment (+) fully matched · partially matched · disjoint (all NaN) Ex 1
Indexing slices .loc inclusive vs .iloc exclusive · label ≠ position Ex 2
Boolean masking mask selects some · mask selects none (empty frame) Ex 3
GroupBy normal groups · a group with one row · NaN/None key dropped Ex 4
GroupBy multi-agg several functions at once · count vs size on missing data Ex 5
Merge how inner () · left · right · outer () · duplicate keys → row explosion Ex 6, Ex 7
Merge edge cases overlapping non-key columns (suffixes=) · multi-key joins Ex 8
Pivot unique cells (plain pivot) · repeated cells → must aggregate Ex 9
Word problem end-to-end: merge → groupby → pivot on real data Ex 10
Exam twist chained-indexing trap + degenerate empty result Ex 11

Ex 1 — Alignment: matched, partial, disjoint


Ex 2 — .loc vs .iloc when label ≠ position


Ex 3 — Boolean masking: some rows vs no rows


Ex 4 — GroupBy with a lone group and a NaN key

The figure below shows the whole split-apply-combine journey for this example. Read it left to right: on the left are the four raw rows (colour-coded by key); the arrows carry each row into its bucket (magenta box for N, violet box for S); the dashed grey arrow shows the row whose key is None being thrown away; inside each box you see the values collected and the mean computed on them. The takeaway: a key of None never reaches any bucket, and a bucket with a single row (S) is still perfectly valid.

Figure — Pandas — Series, DataFrame, indexing, groupby, merge, pivot

Ex 5 — Multi-function agg + count-vs-size on missing data


Ex 6 — Merge: all four how modes on the same tables

The figure below is a Venn diagram of the two tables' id values. What to read from it: the left (magenta) circle holds L's ids, the right (violet) circle holds R's ids; the overlap in the middle is the intersection ; the whole coloured area is the union . Each how mode is just a rule that says which region to keep — inner keeps the overlap, left keeps the whole magenta circle, right keeps the whole violet circle, outer keeps everything. The orange line at the bottom lists all four resulting id-sets.

Figure — Pandas — Series, DataFrame, indexing, groupby, merge, pivot

Ex 7 — Merge with duplicate keys: the row explosion


Ex 8 — Merge edge cases: colliding column names and multi-key joins


Ex 9 — Pivot: unique cells vs repeated cells


Ex 10 — Word problem: full pipeline merge → groupby → pivot


Ex 11 — Exam twist: chained-indexing trap + empty result


Active recall

Recall Cover and answer
  • Q: a + c with disjoint indices — error or all-NaN? → all-NaN, valid Series.
  • Q: .loc[100:300] vs .iloc[0:2] on index [100,200,300,400]? → 3 rows vs 2 rows.
  • Q: A groupby key that is None — where does it go? → coerced to NaN and dropped by default (dropna=False to keep).
  • Q: count vs size on a group [10, NaN]? → count=1 (non-NaN), size=2 (rows).
  • Q: outer row count from left/right/inner? → left + right − inner (inclusion–exclusion).
  • Q: Merge key repeating 2× (L) and 3× (R)? → 2×3 = 6 rows (Cartesian per key).
  • Q: Two tables share a non-key column val — how do you keep both? → suffixes=("_L","_R") (defaults are _x,_y).
  • Q: Row identity is (store,month) — how do you merge? → on=["store","month"] (multi-key join).
  • Q: Duplicate (index,column) in pivot? → pivot raises ValueError; use pivot_table(aggfunc=...).
  • Q: .mean() of an empty selection? → NaN.
  • Q: What do and mean? → intersection (names in both) and union (names in either).