pandas for tabular data
pandas as table algebra: indexes and automatic alignment, selection with loc and iloc under Copy-on-Write, types (categorical, nullable, str, Arrow), split-apply-combine with groupby, joins, and reshaping. Focus on the mental model (everything aligns by labels), validating joins, and writing chained, fast, verifiable transformations saved in columnar format.
After this lesson you can
- Explain how index alignment determines the result of operations on two Series or DataFrames.
- Select and modify data unambiguously with loc and iloc and reason about pandas 3 Copy-on-Write semantics.
- Solve split-apply-combine problems with groupby (agg, transform, filter) and choose between transform and apply.
- Join and reshape tables with merge, concat, pivot_table, and melt, validating join cardinality.
- Choose efficient dtypes and columnar storage (Parquet) for tables with millions of rows.
Before you start
Motivation: a log that no longer fits in a spreadsheet
You run a hyperparameter sweep: three architectures, four learning rates, twenty-five seeds per combination, and twenty epochs per run. That is 6000 rows of metrics, each mixing types: configuration identifier (text), learning rate (real), seed and epoch (integers), accuracy (real). Important questions belong to the same family:
- Which configuration is best on average across seeds, and with how much dispersion? A configuration winning with seed 0 and losing with the other 24 is not better.
- Which runs failed midway, and am I comparing their epoch 6 metrics with epoch 20 metrics of the others?
- How do I join this table with the configuration table storing the complete architecture of each
cfgwithout duplicating rows?
In finance the problem has the same shape: prices by (date, asset), transactions by (date, asset, account), an asset table with sectors. In any machine-learning project, tabular features, labels, and each example’s metadata live in such tables before becoming a tensor.
A spreadsheet quickly becomes insufficient, as does an ndarray: it requires one dtype for the whole matrix and does not know which row represents which run. pandas adds exactly those two things: columns with different dtypes and labels on rows and columns. Everything below uses pandas 3 semantics. In the browser, the first import takes a few seconds:
import numpy as np
import pandas as pd
print("pandas", pd.__version__, "| numpy", np.__version__)The next cell builds the log and answers the first question in four lines:
rng = np.random.default_rng(0)
C, S, E = 12, 25, 20 # configuraciones, semillas, épocas
arch = np.repeat(["mlp", "cnn", "vit"], 4)
lr = np.tile([3e-4, 1e-3, 3e-3, 1e-2], 3)
techo = np.select([arch == "mlp", arch == "cnn"], [0.86, 0.91], 0.89) - 0.04 * np.abs(np.log10(lr / 1e-3))
c, s, e = (m.ravel() for m in np.meshgrid(np.arange(C), np.arange(S), np.arange(1, E + 1), indexing="ij"))
acc = techo[c] * (1 - np.exp(-e / 4)) + rng.normal(0, 0.012, (C, S))[c, s] + rng.normal(0, 0.004, c.size)
log = pd.DataFrame({"cfg": np.array([f"c{i:02d}" for i in range(C)])[c], "arch": arch[c], "lr": lr[c],
"seed": s, "epoch": e, "val_acc": acc})
print(log.shape)
print(log.head(3))
# ¿qué configuración es mejor, y con cuánta dispersión entre semillas?
resumen = (log[log["epoch"] == 20]
.groupby(["arch", "lr"])["val_acc"]
.agg(media="mean", std="std", n="size")
.sort_values("media", ascending=False))
print(resumen.head(4).round(4))Each line of that last expression hides a decision: which rows remain (a mask), how groups are formed, what is calculated in each, and what index the result has. This lesson builds the mental model making those decisions predictable. The central idea fits in one sentence: in pandas, everything matches by labels, not position. Almost everything good about pandas follows from this, and almost all its silent errors too.
Series and DataFrame: labeled arrays
A Series is a pair consisting of a one-dimensional array of values with one dtype and an Index of the same length: the label for each position. A DataFrame is an ordered collection of columns sharing the same row index, plus a second Index of column names. Each column is a Series with its own dtype and internally a contiguous array: pandas stores tables by column, making whole-column operations fast and row-by-row traversal slow.
s = pd.Series([0.91, 0.87, 0.89], index=["cnn", "mlp", "vit"], name="val_acc")
print(s)
print("valores:", s.to_numpy(), "| índice:", s.index)
print("posición de 'vit':", s.index.get_loc("vit"), "| único:", s.index.is_unique, "| creciente:", s.index.is_monotonic_increasing)
df = log.head(4)
print(df.dtypes)
col = df["val_acc"] # una columna es una Series con el índice de la tabla
print(type(col).__name__, col.index.equals(df.index))The Index is central, not decoration. It is an immutable sequence of labels with a lookup structure: when a label is requested, pandas builds a hash table on demand (label to position), so locating it costs expected , as in a dictionary (hash tables are covered in algorithms). Labels can repeat: then get_loc returns a slice if the index is monotonic or a Boolean mask otherwise, and everything that follows (alignment, joining, grouping) must decide what to do with repeats. Properties is_unique and is_monotonic_increasing determine which algorithm pandas uses internally and sometimes what result you obtain.
Also notice column cfg: its dtype is str. Since pandas 3.0 text has its own dtype rather than being stored as generic object. We return to this in the dtypes section because it determines table memory use.
Automatic alignment: the index rules
With NumPy arrays, x + y adds position by position and requires shapes compatible by broadcasting. With Series, the rule differs.
Comparison operators (==, <…) are the exception: between two Series or two DataFrames they do not align, require identical labels, and otherwise raise ValueError: Can only compare identically-labeled Series objects. Their method forms (a.eq(b), a.lt(b)) do align and give False at labels missing from either side.
Proof
In case 2 of the definition, the result index traverses each label in . For label present on both sides all occurrence pairs form, ; if absent on one side, each occurrence on the other pairs with a gap, yielding missing rows. Without repeats, , each label contributes one row, missing exactly when , that is, when .
∎Case 1 deserves attention: with identical indexes, neither sorting nor pairing occurs, even with repeats. a + b with two indexes [b, a, a] gives three rows in that order; if the second were [a, a, b], the same labels in another order, the result would have five rows. Check it in the interactive.
fill_value=0 treats missing values as zero, to_numpy() adds by position without looking at labels, and reset_index(drop=True) discards labels and matches by position. In ‘Filtered column’, which of the four silently gives the wrong result? Enable Int64 to see what happens to dtype.What you should have seen:
- NaNs are information, not an error. In ‘Unordered and overlapping’,
a + bhas five rows: labelsa,dandeappear in only one operand, and the proposition predicts three gaps. Withfill_value=0none remain because each gap counts as zero; if both Series had a gap at the same label, it would remain NaN. - Labels and positions coincide only by chance. In ‘Same labels, different order’,
a + bgives 21, 32 and 13, whereas positional addition gives 11, 22 and 33: perfectly plausible numbers, all wrong if the intent was adding the same configuration. - The most dangerous case raises no error. In ‘Filtered column’,
bresults from keeping some rows of a table, retaining labels 1, 3 and 4. NumPy fails because lengths differ, the best outcome.reset_index(drop=True)on both operands renumbers both indexes 0, 1, 2… and matches position 0 ofb(from row 1) with row 0 ofa: no warning, wrong numbers. - Repeated labels multiply rows. In ‘Repeated labels’,
aappears twice in the first operand and once in the second: two rows. Twice in each would yield four. - A gap changes dtype. NumPy has no missing integer, so one NaN makes an
int64column becomefloat64. With nullable integersInt64, the gap is<NA>and integers remain integers.
The dtype change is not cosmetic. A float64 represents integers exactly only up to , and 64-bit identifiers, nanosecond timestamps, or hashes exceed that. This is NumPy type promotion acting through the back door:
a = pd.Series([1, 2, 3, 4], index=["d", "b", "a", "c"])
b = pd.Series([10, 20, 30], index=["c", "b", "e"])
print("a + b:\n", a + b, sep="")
print("con fill_value=0:", a.add(b, fill_value=0).to_dict())
c = pd.Series([1, 2, 3], index=["a", "b", "c"])
d = pd.Series([10, 20, 30], index=["c", "a", "b"])
print("por etiquetas:", (c + d).to_dict(), "| por posición:", c.to_numpy() + d.to_numpy())
X = pd.DataFrame({"x": [1.0, 2.0, 3.0], "y": [10.0, 20.0, 30.0]})
print("media por columna restada:\n", X - X.mean(), sep="")
print("columnas tras X - X.mean(axis=1):", list((X - X.mean(axis=1)).columns))
print("bien hecho, con sub(axis=0):\n", X.sub(X.mean(axis=1), axis=0), sep="")
ids = pd.Series([2**53 + 1, 7], index=["p", "q"])
print(ids.reindex(["p", "q", "r"]).dtype, int(ids.reindex(["p", "q", "r"])["p"]) - 2**53)
print(ids.astype("Int64").reindex(["p", "q", "r"]).tolist())The DataFrame part is the most frequent trap in the lesson. X - X.mean() works because X.mean() is a Series indexed by column names, and a DataFrame minus a Series aligns the Series index with columns. But X.mean(axis=1) is indexed by rows 0, 1 and 2; when subtracting it, pandas seeks columns named 0, 1 and 2, finds none, and returns a five-column table full of NaN. Explicitly state the axis to align against: X.sub(m, axis=0).
The last line is promotion in action: identifier becomes float64 when a gap appears and returns as without error. With Int64 it survives intact.
Selection: loc, iloc, and Copy-on-Write
There are two ways to specify rows and columns; avoid mixing them:
| Accessor | Selects by | Slice a:b | Example |
|---|---|---|---|
df.loc[filas, cols] | labels | includes endpoint b | log.loc[log["seed"] == 0, ["cfg", "val_acc"]] |
df.iloc[filas, cols] | integer positions | excludes b, as in Python | log.iloc[:5, -1] |
df[mask] | Boolean row mask | log[log["epoch"] == 20] | |
df.query("...") | text expression over columns | log.query("lr > 1e-3 and arch == 'vit'") |
loc including the right endpoint is not arbitrary: labels have no “next” value, and s.loc["b":"d"] should mean “from b through d.” A Boolean mask that is a Series also aligns by index before selection, so a mask calculated on another table in a different order selects the correct rows (with df[mascara], pandas emits a UserWarning that it reordered it). Mask labels absent from the table are ignored, but if the mask lacks a table label, pandas raises IndexingError rather than deciding whether to include that row.
The classic ambiguity is bare brackets with integers. If the index consists of unordered integers, t.loc[0] is the row with label 0 and t.iloc[0] the first row: different things. pandas 3 also removed the last positional fallback: s[0] on a Series with text labels no longer returns the first element; it raises KeyError.
Copy-on-Write
For years, “does this return a view or a copy?” was pandas’ greatest source of confusion, because the answer depended on internal dtype and table-shape details. pandas 3.0 resolved it by changing the rules.
Three direct consequences:
- Chained assignment never works. In
df[df["a"] > 0]["b"] = 1, the first brackets produce a new object behaving like a copy; assignment modifies that copy, immediately discarded. pandas 3 emitsChainedAssignmentErroras a warning anddfdoes not change. The same applies todf["b"][mascara] = 1anddf.loc[0]["a"] = 5. The correct way is one call to the indexer:df.loc[mascara, "b"] = 1. SettingWithCopyWarningdisappears. No guessing is needed:sub = df[mascara]followed bysub["b"] = 1modifiessuband neverdf, without warnings, exactly as the rules say.- Defensive copies are unnecessary.
reset_index,rename,set_index, or column selection no longer copy data until someone writes, so chaining transformations costs little memory. In exchange,to_numpy()and.valuesreturn read-only arrays when sharing memory with the table: writing to them raisesValueErrorrather than silently corrupting the DataFrame.
import warnings
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])
print(s.loc["b":"c"].tolist(), s.iloc[1:3].tolist())
t = pd.Series([1.0, 2.0, 3.0], index=[2, 0, 1])
print("t.loc[0] =", t.loc[0], "| t.iloc[0] =", t.iloc[0])
try:
s[0]
except KeyError as e:
print("s[0] -> KeyError", e)
df = pd.DataFrame({"a": [1, -1, 2], "b": [0, 0, 0]})
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
df[df["a"] > 0]["b"] = 1 # asignación encadenada
print("encadenada:", df["b"].tolist(), "|", type(w[0].message).__name__)
df.loc[df["a"] > 0, "b"] = 1 # una sola llamada a loc
print("con loc: ", df["b"].tolist())
col = df["a"] # copia perezosa: comparte memoria
print("comparten memoria:", np.shares_memory(col.to_numpy(), df["a"].to_numpy()))
col.iloc[0] = 99 # la primera escritura copia
print("tras escribir: df['a'] =", df["a"].tolist(), "| col =", col.tolist(),
"| comparten:", np.shares_memory(col.to_numpy(), df["a"].to_numpy()))
print("to_numpy() escribible:", df["a"].to_numpy().flags.writeable)The output shows the full mechanism: col and df["a"] share memory until col is written; at that moment col receives its own copy and df remains intact.
groupby: split, apply, combine
You already built group aggregation from scratch in the advanced-indexing lab: factorize keys into integer codes, scatter with bincount, and collect. pandas generalizes it to a named pattern formulated by Hadley Wickham in 2011.
By default groups come out sorted by key (sort=True), missing keys (NaN) are discarded (dropna=True), and with categorical keys only observed categories appear (observed=True, the default since pandas 3.0).
agg, transform, and filter and notice output shape and index: agg returns one row per group with key as index, transform returns one row per original row and, in the last act, rows return to position carrying their value. Click a cfg cell to change a row's group: what happens to standard deviation and z-score when a group has only one row?The distinction between agg and transform matters most in practice. agg answers questions about groups (“what is each configuration’s mean accuracy?”), and its result cannot be pasted as an original-table column because it has another index. transform answers questions about each row in its group’s context (“how far is this run from its configuration mean?”), and its result has exactly the table’s index, so df["centrada"] = df["acc"] - g.transform("mean") works by alignment. They are related by an identity connecting to gather and scatter:
Proof
By definition, transform(f) assigns each row the value of on its own group, , so it is . In code this is gather, r[codigos]. For filter, row is retained exactly if its group passes, i.e. : Boolean mask p[codigos] applied to the table, and a mask does not reorder.
In other words: agg with a reduction is scatter (each row contributes to its group cell), and transform and filter gather back. If keys are missing (with default dropna=True), those rows belong to no group: transform gives them NaN and filter discards them. That is why transform output aligns with the original at no extra cost.
final = log[log["epoch"] == 20]
g = final.groupby("cfg")["val_acc"]
por_cfg = final.groupby("cfg").agg(media=("val_acc", "mean"), std=("val_acc", "std"), n=("seed", "nunique"))
print(por_cfg.head(3).round(4), por_cfg.shape)
print("transform:", g.transform("mean").shape, "| índice igual al de final:", g.transform("mean").index.equals(final.index))
codigos, grupos = pd.factorize(final["cfg"], sort=True)
print("transform == agg[códigos]:", np.allclose(g.transform("mean").to_numpy(), g.mean().to_numpy()[codigos]))
estables = final.groupby("cfg").filter(lambda d: d["val_acc"].std() < 0.0125)
print("filter:", final.shape, "->", estables.shape, "| configuraciones que quedan:", estables["cfg"].nunique())
mejor = final.groupby("cfg")[["seed", "val_acc"]].apply(lambda d: d.loc[d["val_acc"].idxmax()])
print(mejor.head(2))Syntax agg(media=("val_acc", "mean"), ...) is named aggregation: each argument creates an output column from an input column and function, avoiding the two-level column names produced by agg({"val_acc": ["mean", "std"]}). Notice std: pandas defaults to sample standard deviation with in the denominator (ddof=1, the unbiased variance version), while np.std uses (ddof=0). With 25 seeds the difference is 2%; for a one-row group pandas returns NaN and NumPy 0.
When to use transform and when apply
apply is the most general and slowest tool: it calls your Python function once per group and then must guess how to combine returns. Use it only when the operation cannot be expressed otherwise (such as “the row with best accuracy per group,” although even that has vectorized df.loc[g.idxmax()]). String-named functions ("mean", "std", "max", "cumsum", "rank"…) have compiled implementations traversing the table once, like bincount in the indexing lesson:
import time
def medir(f, rep=3):
t = []
for _ in range(rep):
t0 = time.perf_counter(); f(); t.append(time.perf_counter() - t0)
return min(t)
rng = np.random.default_rng(5)
grande = pd.DataFrame({"g": rng.integers(0, 2_000, 40_000), "x": rng.normal(size=40_000)})
gb = grande.groupby("g")["x"]
cod = pd.factorize(grande["g"])[0]
x = grande["x"].to_numpy()
for nombre, f in [("transform('mean')", lambda: gb.transform("mean")),
("transform(lambda)", lambda: gb.transform(lambda s: s.mean())),
("apply por grupo", lambda: gb.apply(lambda s: s - s.mean())),
("bincount + gather", lambda: (np.bincount(cod, x) / np.bincount(cod))[cod])]:
print(f"{nombre:20s} {medir(f, rep=2) * 1e3:8.2f} ms")With 2000 groups, passing a lambda costs two orders of magnitude more than the string name even when calculating the same thing: time is dominated by the Python call per group, not arithmetic. The bincount and gather version confirms the proposition and marks the performance limit. Rule of thumb: if a string name exists for what you want, use it; otherwise try composing several ((x - g.transform("mean")) / g.transform("std")); apply is the last resort.
Lab: a minimal Series from scratch
To check the mental model is complete, implement it. MiniSeries stores lists of values and labels, builds a hash table from label to positions, and adds with alignment exactly following the definition, including two often-forgotten cases: identical indexes (position by position, no sorting) and repeated labels (Cartesian product). We also add one-pass groupby_sum using a dictionary.
class MiniSeries:
"""Array con etiquetas: valores, índice y operaciones alineadas, como una Series."""
def __init__(self, values, index):
assert len(values) == len(index)
self.values = [float(v) for v in values]
self.index = list(index)
def __repr__(self):
return "\n".join(f"{k!s:>4} {v}" for k, v in zip(self.index, self.values))
def _posiciones(self):
pos = {}
for p, k in enumerate(self.index):
pos.setdefault(k, []).append(p) # el índice como tabla hash: etiqueta -> posiciones
return pos
def _binaria(self, other, f, fill=None):
if self.index == other.index: # índices idénticos: posición a posición
return MiniSeries([f(x, y) for x, y in zip(self.values, other.values)], self.index)
pa, pb = self._posiciones(), other._posiciones()
nan = float("nan")
vals, idx = [], []
for k in sorted(pa.keys() | pb.keys()): # unión ordenada de las etiquetas
for i in pa.get(k, [None]):
for j in pb.get(k, [None]): # producto cartesiano de las repetidas
x = self.values[i] if i is not None else fill
y = other.values[j] if j is not None else fill
vals.append(nan if x is None or y is None else f(x, y))
idx.append(k)
return MiniSeries(vals, idx)
def __add__(self, other):
return self._binaria(other, lambda x, y: x + y)
def add(self, other, fill_value=None):
return self._binaria(other, lambda x, y: x + y, fill=fill_value)
def groupby_sum(self, keys):
acc = {}
for k, v in zip(keys, self.values): # split y apply en una pasada
acc[k] = acc.get(k, 0.0) + v
ks = sorted(acc) # combine: una fila por clave, ordenadas
return MiniSeries([acc[k] for k in ks], ks)
a = MiniSeries([1, 2, 3, 4], ["d", "b", "a", "c"])
b = MiniSeries([10, 20, 30], ["c", "b", "e"])
print(a + b)Now compare with pandas, the reference implementation, on random cases with repeated and missing labels:
def iguales(mini, ser):
return (mini.index == list(ser.index)
and np.allclose(mini.values, ser.to_numpy(dtype=float), equal_nan=True))
rng = np.random.default_rng(1)
casos = 0
for _ in range(200):
la = list(rng.choice(list("abcd"), size=rng.integers(1, 6)))
lb = list(rng.choice(list("abcd"), size=rng.integers(1, 6)))
va, vb = rng.integers(0, 9, len(la)), rng.integers(0, 9, len(lb))
m = MiniSeries(va, la) + MiniSeries(vb, lb)
p = pd.Series(va, index=la, dtype=float) + pd.Series(vb, index=lb, dtype=float)
mf = MiniSeries(va, la).add(MiniSeries(vb, lb), fill_value=0)
pf = pd.Series(va, index=la, dtype=float).add(pd.Series(vb, index=lb, dtype=float), fill_value=0)
casos += iguales(m, p) and iguales(mf, pf)
print(f"coinciden con pandas en {casos} de 200 casos aleatorios")
dup = MiniSeries([1, 2], ["a", "a"]) + MiniSeries([10, 20, 30], ["a", "a", "b"])
print(dup)
claves = ["x", "y", "x", "z", "y"]
v = MiniSeries([1, 2, 3, 4, 5], range(5))
print("groupby_sum:", v.groupby_sum(claves).values,
"| pandas:", pd.Series([1, 2, 3, 4, 5.0]).groupby(claves).sum().tolist())They match in every case, including row order: within a repeated label, pandas traverses occurrences of the left operand first, as dup output (11, 21, 12, 22) shows. Differences from the real implementation are scale rather than semantics: pandas factorizes labels with a compiled hash table, operates on NumPy arrays instead of lists, and if both indexes are monotonic uses a sorted-list merge algorithm needing no hash table.
Tidy data and reshaping
Before joining and pivoting tables, establish the desired shape.
The motivation’s log is long and tidy: one row per (run, epoch). The accuracy table with one column per learning rate is wide: convenient to inspect, inconvenient to group or join. Configurations are a different observational unit (one row per cfg, not per epoch) and belong in their own table. Repeating the complete architecture in each of 6000 rows wastes memory and, worse, permits two rows of the same configuration to contradict each other. That is why multiple tables are joined when needed.
merge: cardinality decides
L.merge(R, on="cfg", how=...) matches each row of L to all rows of R with the same key, like an SQL join. Join type decides what happens to unmatched keys: inner discards them, left keeps those of L (filling with NaN), right those of R, and outer those on both sides. Result row count can be computed in advance.
Proof
Rows with different keys do not interact, so the result is the disjoint union of key-wise results. For key with , each of the rows of matches each of the rows of : rows for every join type. If , inner produces nothing, while left and outer retain the rows of with gaps, which is ; symmetrically for . Summing over yields the three formulas. For the final equivalence, , and difference is a sum of nonnegative terms, zero exactly when every key of (those with ) has .
The practical consequence is serious. If runs are joined to configurations and someone registered c03 twice, every c03 run is duplicated: the table has more rows than runs, and any later mean weights c03 twice. There is no error or warning. In the worst case, one key with and rows produces : two million-row tables with one constant key yield rows, and the join never finishes. Detect this with validate: using "one_to_one", "one_to_many", or "many_to_one", pandas checks before joining that the corresponding side’s keys are unique and otherwise raises MergeError.
B appears twice with different learning rates. Each line is a result row. Look at rows per key: with inner, 5 runs give 6 rows because B contributes and unmatched C disappears. Choose validate='many_to_one' to see pandas detect it before joining. Click keys to change them, try all four join types, and enable indicator=True: _merge says where each row comes from. Hover over a result row to see its match.Two further details the interactive reveals. First, row order: inner and left traverse L in order and, for each row, its matches in R; outer sorts keys. Second, indicator=True adds categorical column _merge, with values both, left_only, and right_only: a clean way to find orphans, runs whose configuration does not exist or configurations never run.
runs = (log[["cfg", "arch", "lr", "seed"]].drop_duplicates(["cfg", "seed"])
.assign(run_id=lambda d: d["cfg"] + "-s" + d["seed"].astype(str)))
configs = runs[["cfg", "arch", "lr"]].drop_duplicates("cfg").reset_index(drop=True)
mala = pd.concat([configs, configs.iloc[[3]].assign(lr=0.5)], ignore_index=True) # c03 registrada dos veces
ok = runs[["run_id", "cfg"]].merge(configs, on="cfg", how="left", validate="many_to_one")
print(len(runs), "->", len(ok))
print(len(runs), "->", len(runs[["run_id", "cfg"]].merge(mala, on="cfg", how="left")), "filas sin validar")
try:
runs[["run_id", "cfg"]].merge(mala, on="cfg", how="left", validate="many_to_one")
except pd.errors.MergeError as e:
print("MergeError:", str(e).splitlines()[0])
huerfanas = pd.DataFrame({"run_id": ["c99-s0", "c00-s0"], "cfg": ["c99", "c00"]})
m = huerfanas.merge(configs, on="cfg", how="left", indicator=True)
print(m[["run_id", "_merge"]])The 25 runs of c03 become 50, and the total rises from 300 to 325, exactly as the theorem predicts: . With validate="many_to_one" the join does not even begin.
concat, pivot_table, melt, stack, and unstack
pd.concat stacks tables. With axis=0 (one below another) it aligns columns by name: if one table has a column the other lacks, the result includes it with gaps where missing. With axis=1 (side by side) it aligns row indexes under the same automatic-alignment rules. ignore_index=True discards input indexes and renumbers, usually desired when stacking row batches.
To change between long and wide format there are four operations, two in each direction:
- Long to wide:
pivot(index, columns, values)requires each (row, column) pair to appear once and fails otherwise;pivot_tableaccepts repeats and aggregates them, by mean by default (aggfunc="mean"). - Wide to long:
melt(id_vars, var_name, value_name)turns columns into rows. - With hierarchical indexes:
stackmoves the column level to the row index (aMultiIndex) andunstackdoes the reverse. AMultiIndexhas tuple labels such as (architecture, rate) or (entity, date).
ancha = final.pivot_table(index="arch", columns="lr", values="val_acc", aggfunc="mean")
print(ancha.round(3))
larga = ancha.reset_index().melt(id_vars="arch", var_name="lr", value_name="val_acc")
print(larga.shape, "| ida y vuelta:", np.allclose(larga.pivot(index="arch", columns="lr", values="val_acc"), ancha))
apilada = ancha.stack() # columnas -> nivel interior del índice
print(apilada.index.names, apilada.shape, "| unstack devuelve la ancha:", apilada.unstack().equals(ancha))
try:
final.pivot(index="arch", columns="lr", values="val_acc")
except ValueError as e:
print("pivot:", e)The last line is the crucial difference: final has 25 rows per (architecture, rate) pair, one per seed, and pivot refuses to choose. pivot_table does not refuse: it silently averages. If you expected one row per pair, that average hides a duplicate you should have seen; otherwise at least specify aggfunc explicitly so readers know aggregation occurs.
dtypes: what each column occupies
Each column has a dtype, which determines three things: what values fit, how a missing value is represented, and how much memory the column occupies. pandas 3 combines three type families, and choosing well can determine whether a table fits in memory.
A categorical column’s memory can be calculated mentally. With rows and categories, codes occupy bytes, where is the smallest integer size pandas considers sufficient (1 byte with , 2 with , 4 above that), and categories are stored once. Code is reserved for missing. Text such as "efficientnet_b0", by contrast, occupies a CPython object with a header of several dozen bytes (40 on a 64-bit machine) plus one byte per character and one terminator, and the column additionally stores a pointer per row: 8 bytes on a 64-bit machine and 4 in the browser, which runs Python compiled to 32-bit WebAssembly. The difference is tens of times:
n = 300_000
rng = np.random.default_rng(2)
nombres = np.array(["resnet18", "vit_small", "mlp_mixer", "convnext_t", "efficientnet_b0"])
x = nombres[rng.integers(0, 5, n)]
for dt in [object, "str", "category"]:
col = pd.Series(x, dtype=dt)
print(f"{str(dt):>22s} dtype={str(col.dtype):9s} {col.memory_usage(deep=True, index=False) / 1e6:7.2f} MB "
f"(sin deep: {col.memory_usage(index=False) / 1e6:5.2f} MB)")
cat = pd.Series(x, dtype="category")
print("códigos:", cat.cat.codes.dtype, cat.cat.codes.nbytes / 1e6, "MB | categorías:", list(cat.cat.categories))
print("dtype de str:", repr(pd.Series(["a"]).dtype))
for k in (126, 127, 40_000):
print(k, "categorías -> códigos", pd.Series(np.arange(k).astype(str)).astype("category").cat.codes.dtype)Three readings of the output:
memory_usage()withoutdeep=Truemisleads on text. Forobjectit counts only pointers, one per row; Python object contents, almost everything, appear only withdeep=True.- The
strdtype depends on whether pyarrow is installed. In the browser it is not, andstrstores Python objects: it occupies the same asobject, though it knows all elements are text (and missing isNaN). On your machine, with pyarrow,strstores characters consecutively in one buffer plus an offset array, and the same column occupies about 5.5 MB, three times less. categorywins decisively with few categories: 300 000 bytes ofint8codes and five strings. With many distinct categories (a unique identifier per row), the advantage disappears because categories occupy as much as the original column.
Nullable integers cost one more byte per row than NumPy integers (the mask is a Boolean array), and Arrow integers one bit. In return they lose neither precision nor type when a gap appears, as with identifier .
Lab: a real experiment log
Real logs are not as clean as the motivation’s. This lab starts from a CSV of 27 configurations (architecture, learning rate, and weight decay) with 40 seeds each, 1080 runs and 10 epochs per run, with typical flaws: architecture names with inconsistent capitalization and spaces, runs failing midway (their final epochs have missing metrics), and a duplicate row caused by a logging retry.
import io
rng = np.random.default_rng(3)
cfgs = [(a, l, w) for a in ["MLP", " cnn", "ViT "] for l in [3e-4, 1e-3, 3e-3] for w in [0.0, 0.01, 0.1]]
lineas = ["run_id,arch,lr,weight_decay,seed,epoch,val_loss,val_acc"]
base = {"mlp": 0.86, "cnn": 0.91, "vit": 0.89}
for c, (a, l, w) in enumerate(cfgs):
for seed in range(40):
rid = f"r{c:02d}{seed:02d}"
techo = base[a.strip().lower()] - 0.03 * abs(np.log10(l / 1e-3)) - 0.2 * w + rng.normal(0, 0.01)
fallo = rng.random() < 0.03 # un 3 % de las ejecuciones se cae en la época 7
for ep in range(1, 11):
acc = techo * (1 - np.exp(-ep / 3)) + rng.normal(0, 0.003)
loss = -np.log(max(acc, 1e-3))
if fallo and ep > 6:
lineas.append(f"{rid},{a},{l},{w},{seed},{ep},nan,NA")
else:
lineas.append(f"{rid},{a},{l},{w},{seed},{ep},{loss:.4f},{acc:.4f}")
lineas.append(lineas[1234]) # reintento del registro: fila duplicada
csv = "\n".join(lineas)
print(f"{len(lineas) - 1} filas, {len(csv) / 1e6:.2f} MB de texto")The first step is read, inspect, and type. Write cleaning as method chaining: each step receives the preceding table and returns a new one, without intermediate variables or in-place modifications. With Copy-on-Write the chain does not copy data unnecessarily, and assign with a lambda can refer to the table as it stands at that point in the chain.
crudo = pd.read_csv(io.StringIO(csv))
print(crudo.dtypes.to_dict())
print("arch distintos:", sorted(crudo["arch"].unique()))
limpio = (crudo
.drop_duplicates()
.assign(arch=lambda d: d["arch"].str.strip().str.lower().astype("category"),
run_id=lambda d: d["run_id"].astype("category"),
seed=lambda d: d["seed"].astype("int16"),
epoch=lambda d: d["epoch"].astype("int8")))
print(len(crudo), "->", len(limpio), "filas | arch:", list(limpio["arch"].cat.categories))
mem = lambda d: d.memory_usage(deep=True).sum() / 1e6
print(f"memoria: {mem(crudo):.2f} MB -> {mem(limpio):.2f} MB")
con_huecos = limpio["val_acc"].isna().groupby(limpio["run_id"], observed=True).any()
print("ejecuciones con métricas ausentes:", int(con_huecos.sum()), "de", len(con_huecos))read_csv recognized nan and NA as missing without being asked, and read arch with three values that are the same text inconsistently spelled: grouping now would treat " cnn" and "cnn" as different configurations. After cleaning and typing, the table occupies two to three times less in the browser; on your machine with pyarrow, input text is already more compact and the reduction is half. The last line is groupby without apply: a Boolean mask grouped by run and reduced with any.
Now the real question: which configuration is best on average across seeds? It is tempting to take each run’s last valid epoch and average. But failed runs have their last valid epoch at 6, halfway along the learning curve, and comparing them with those reaching 10 mixes different things:
validas = limpio.dropna(subset=["val_acc"])
ultima = validas.loc[validas.groupby("run_id", observed=True)["epoch"].idxmax()] # última época válida
completa = ultima["epoch"] == limpio["epoch"].max()
claves = ["arch", "lr", "weight_decay"]
resumir = lambda d: d.groupby(claves, observed=True)["val_acc"].agg(media="mean", std="std", n="size")
comparacion = resumir(ultima).join(resumir(ultima[completa]), lsuffix="_todas", rsuffix="_completas")
cols = ["media_todas", "media_completas", "std_todas", "std_completas", "n_completas"]
print(comparacion.sort_values("media_completas", ascending=False)[cols].head(4).round(4).to_string())
tabla = resumir(ultima[completa])["media"].unstack("lr").xs(0.0, level="weight_decay")
print(tabla.round(3))The first row tells the story. With all runs, configuration cnn with lr = 1e-3 and no weight decay has mean 0.8714 and deviation 0.026, ranking behind the same configuration with weight_decay = 0.01. With only completed runs, its mean rises to 0.8780, deviation falls to 0.0107, matching the others, and it becomes best. Three failed runs out of 40 sufficed to reverse the order. Discarding failures is not innocent either: if a configuration fails more than others (a divergent learning rate, for example), keeping survivors favors it. Report both the metric among completed runs and the failure rate per configuration. This is the same problem as financial-data survivorship bias; evaluation with several seeds has its own lesson in multi-seed evaluation.
The final table is wide format for inspection: architectures in rows, rates in columns, using xs to fix one MultiIndex level.
Performance: vectorize, chain, and store by column
pandas is fast when each operation traverses whole columns in compiled code, and slow when Python code runs once per row. This is the same lesson as NumPy vectorization, with an extra complication: each DataFrame row does not exist as an object, and constructing it costs time.
m = 10_000
tabla = pd.DataFrame({"precio": rng.uniform(1, 100, m), "cantidad": rng.integers(1, 50, m),
"lado": rng.choice(["compra", "venta"], m)})
def con_iterrows(d):
out = []
for _, fila in d.iterrows(): # cada fila se convierte en una Series
signo = 1 if fila["lado"] == "compra" else -1
out.append(signo * fila["precio"] * fila["cantidad"])
return np.array(out)
def con_itertuples(d):
return np.array([(1 if f.lado == "compra" else -1) * f.precio * f.cantidad for f in d.itertuples(index=False)])
def con_apply(d):
return d.apply(lambda f: (1 if f["lado"] == "compra" else -1) * f["precio"] * f["cantidad"], axis=1).to_numpy()
def vectorizado(d):
return np.where(d["lado"] == "compra", 1, -1) * d["precio"].to_numpy() * d["cantidad"].to_numpy()
ref = vectorizado(tabla)
for f in (con_iterrows, con_itertuples, con_apply, vectorizado):
t = medir(lambda: f(tabla), rep=1 if f is not vectorizado else 5)
print(f"{f.__name__:15s} {t * 1e3:8.1f} ms {t / m * 1e6:7.2f} µs por fila correcto: {np.allclose(f(tabla), ref)}")iterrows constructs a Series per row with its index and dtype. Since a Series has one dtype, a row with an integer, float, and text becomes object, and a row with only integers and floats becomes float64: integers are converted along the way. itertuples is an order of magnitude cheaper because it returns named tuples, and apply(axis=1) is a Python loop with a nicer interface. The vectorized version is two to three orders of magnitude faster than iterrows, depending on machine: with ten million rows, the difference between one second and several minutes.
Three habits complete the picture:
- Chain methods. A transformation written as a chain (
.query(...),.assign(...),.groupby(...),.pipe(f)) reads top to bottom, leaves no half-built variables, and is tested as a function.inplace=Truesaves neither memory nor time in almost any case and breaks the chain; Copy-on-Write has removed the little sense it had. - Store in Parquet, not CSV. CSV is text: every number needs conversion on read, dtypes are not stored (categories and small integers return as text and
int64), and one column cannot be read without all others. Parquet is a binary columnar format compressed by column with types in metadata; read only needed columns and skip row blocks failing a filter, because each block stores each column’s minimum and maximum. - Know when to look at polars. pandas runs almost everything on one thread and evaluates each step immediately. polars, built on Arrow format, parallelizes by default and has a lazy API optimizing the whole query before execution (for example, pushing filters into the Parquet read). For tens-of-millions-row tables with many aggregations it can be considerably faster. It has no index: everything is positional or by columns, eliminating automatic alignment, for better and worse.
The CSV versus Parquet comparison needs actual files and a large table, so it runs on your machine:
import os, tempfile, time
import numpy as np
import pandas as pd
n = 1_000_000
rng = np.random.default_rng(0)
df = pd.DataFrame({
"run_id": pd.Categorical.from_codes(rng.integers(0, 10_000, n), [f"r{i:05d}" for i in range(10_000)]),
"arch": pd.Categorical.from_codes(rng.integers(0, 3, n), ["cnn", "mlp", "vit"]),
"epoch": rng.integers(1, 101, n).astype("int16"),
"lr": rng.choice([3e-4, 1e-3, 3e-3], n),
"val_loss": rng.gamma(2.0, 0.3, n),
"val_acc": rng.uniform(0.5, 0.95, n),
})
print(f"{n:,} filas, {df.memory_usage(deep=True).sum() / 1e6:.0f} MB en memoria")
def mejor_de(f, rep=3):
t = []
for _ in range(rep):
t0 = time.perf_counter(); out = f(); t.append(time.perf_counter() - t0)
return out, min(t)
with tempfile.TemporaryDirectory() as d:
csv, pq = os.path.join(d, "log.csv"), os.path.join(d, "log.parquet")
_, t_wc = mejor_de(lambda: df.to_csv(csv, index=False), rep=1)
_, t_wp = mejor_de(lambda: df.to_parquet(pq, index=False), rep=1)
df_c, t_rc = mejor_de(lambda: pd.read_csv(csv))
df_p, t_rp = mejor_de(lambda: pd.read_parquet(pq))
_, t_r2 = mejor_de(lambda: pd.read_parquet(pq, columns=["arch", "val_acc"]))
print(f"CSV: {os.path.getsize(csv) / 1e6:6.1f} MB escribir {t_wc:5.2f} s leer {t_rc:5.2f} s")
print(f"Parquet: {os.path.getsize(pq) / 1e6:6.1f} MB escribir {t_wp:5.2f} s leer {t_rp:5.2f} s")
print(f"Parquet, solo 2 columnas: {t_r2:.3f} s")
print("dtypes tras CSV: ", df_c.dtypes.astype(str).to_dict())
print("dtypes tras Parquet:", df_p.dtypes.astype(str).to_dict())
print("Parquet devuelve exactamente la tabla:", df_p.equals(df))npm run lab and open the connection link.The robust part of the comparison is not full-read times, which depend heavily on CSV reader and disk, but the rest. CSV occupies about three times more and takes much longer to write because each float is formatted as text with all its digits. Reading returns str and int64 where there were categories and int16, requiring retyping on each read. Parquet returns exactly the same table with its dtypes, and when only two columns are requested it does not read the rest from disk: savings grow with the number and size of skipped columns.
Common mistakes
Exercises
a = pd.Series([5, 1, 2], index=['y', 'x', 'z']) and b = pd.Series([10, 20, 30, 40], index=['x', 'w', 'y', 'x']), what does a + b return?df = pd.DataFrame({'lr': [3e-3, 1e-4, 1e-2], 'seed': [0, 1, 2]}), which instructions modify df?More than one answer may be correct.
df has 1000 rows, with 40 distinct configurations in cfg and 25 rows per configuration. Which expressions return exactly 1000 rows?More than one answer may be correct.
X is a DataFrame of 3 rows and 2 float columns, x and y. Which expressions subtract each row's own mean and return a 3 by 2 table?More than one answer may be correct.
category. How many MB ( bytes) do its codes occupy?L has keys A, A, A, B, B, C and R has A, A, A, B, D, D, D, D. How many rows does L.merge(R, on='k', how='outer') return?Step 1 of 3. How do you organize the pair count?
zscore_por_grupo(df, clave, col), returning a Series with df's index and, in each row, the z-score of df[col] within its df[clave] group: , with the group's sample standard deviation (ddof=1, pandas' version). In one-row groups or where all values are equal, the deviation is unusable: return 0.0. No Python loops or apply: tests include 5000 groups and an unordered index, and df must not be modified.import numpy as np
import pandas as pd
def zscore_por_grupo(df, clave, col):
# devuelve una Series con el índice de df: (x - media del grupo) / std del grupo (ddof=1)
# en grupos de una sola fila o con desviación nula, el z-score es 0.0
passunir_validando(runs, configs). runs has one row per run with key cfg; configs has one row per configuration with key cfg and hyperparameters. Return a tuple (unidas, huerfanas): unidas is the left join of runs with configs, with all runs in order and no auxiliary columns; huerfanas contains rows of runs (only its columns, in original order) whose cfg does not exist in configs. If configs has a repeated key, the function must raise pandas.errors.MergeError instead of multiplying rows. Use validate and indicator.import pandas as pd
def unir_validando(runs, configs):
# 1. une cada ejecución con su configuración (how="left") y valida que configs tenga claves únicas
# 2. devuelve (unidas, huerfanas): unidas sin columna auxiliar; huerfanas, las filas de runs
# (solo sus columnas, en su orden original) cuya cfg no aparece en configs
passSummary
transform returns results aligned to the original table, and merge matches rows by key, with rows per key. Most silent errors are unexpected alignments; most solutions make the desired alignment explicit.- Series and DataFrame are labeled arrays stored by column, each with its own dtype. The
Indexis a lookup structure (hash table) permitting repeats. - Alignment: identical indexes operate by position; otherwise by outer union of labels.
fill_value,reindex,align, andto_numpy()make another rule explicit. In a DataFrame, a Series aligns with columns unless you specifyaxis=0. - Selection:
locby labels (inclusive slices),ilocby positions. With Copy-on-Write, every derived object behaves like a copy: chained assignment does not work and correct modification uses one call tolocoriloc. - groupby:
agggives one row per group,transformone per row aligned with the table (a gather of aggregates),filtera subset. Prefer string-named functions tolambdaandapply. - Tidy data and joins: one observation per row, one table per unit. A join has matched rows;
validatechecks uniqueness before joining andindicatorfinds orphans.pivot_tableandmeltswitch between wide and long formats. - dtypes and storage:
categoryfor text with few distinct values, nullable integers with gaps,memory_usage(deep=True)to measure, and Parquet to store typed, compressed tables readable by column.