Skip to content
BIASED

Data frames with pandas

Tables in pandas 3: Series and DataFrame as named columns over arrays, alignment on labels, loc against iloc, Copy-on-Write and chained assignment, missing values and dtypes, reading CSV, filtering, groupby, merges, pivot tables, a little time series, and two traps: row loops and leakage.

Columns over arrays

The topic NumPy arrays ended with what an array cannot hold. An array has one dtype, and you find an element by its position. Real data come as tables: a column of run names next to a column of losses and a column of dates, rows found by a key, some values missing. The topic Files and exceptions read such a table, metrics.csv, with the csv module and got every field back as a string.

pandas stores a table as a DataFrame. The examples use Python 3.14.7, pandas 3.1.0 and NumPy 2.5.4, without PyArrow, run with uv run --python 3.14 --with "pandas>=3" python. From the second session on, import numpy as np and import pandas as pd are assumed.

>>> import pandas as pd
>>> df = pd.DataFrame({"run": ["a", "b", "c"],
...                    "loss": [0.58, 0.49, 0.80],
...                    "epochs": [3, 3, 2]})
>>> df
  run  loss  epochs
0   a  0.58       3
1   b  0.49       3
2   c  0.80       2
>>> df.dtypes
run           str
loss      float64
epochs      int64
dtype: object
>>> df.index
RangeIndex(start=0, stop=3, step=1)
>>> type(df["loss"]).__name__, df["loss"].to_numpy()
('Series', array([0.58, 0.49, 0.8 ]))

Key idea. A Series is a one-dimensional array of values plus an Index of labels, one label per value. A DataFrame is a set of named columns that share one row Index. Each column is a Series with its own dtype, stored as a NumPy array or a pandas array of its own.

Here loss is a NumPy float64 array, epochs is int64, and run has the dtype str, the default for text since pandas 3.0. With no index given, pandas numbers the rows 0, 1, 2. That RangeIndex stores only its start, stop and step, so it costs no memory. df["loss"] is one column, a Series, and .to_numpy() returns the array underneath.

Why columns. Analysis works column by column, so pandas stores a table that way. df["loss"].mean() is one NumPy reduction over one array. Reading one row is the expensive direction: it must collect a value from every column and, with mixed dtypes, wrap them into Python objects. This decides which pandas code is fast, as the block on row loops measures.

Alignment. Arithmetic between two Series matches values by label, not by position. A label present in only one of them gives NaN, the floating-point "not a number" that pandas uses for a missing value:

>>> s = pd.Series([0.92, 0.85, 0.95], index=["a", "b", "c"])
>>> u = pd.Series([0.58, 0.49], index=["b", "a"])
>>> s - u
a    0.43
b    0.27
c     NaN
dtype: float64

u lists b before a, and the subtraction still pairs a with a: 0.92−0.49=0.430.92 - 0.49 = 0.43. Label c has no partner, so its result is missing.

Labels and positions

Rows have labels and positions, and the two can differ. So pandas has two indexers.

The rule.

  • .loc[...] selects by label. A slice of labels includes both ends: s.loc["a":"b"] holds a and b.
  • .iloc[...] selects by position, like a list. A slice excludes its end: s.iloc[0:1] holds one element.
  • On a DataFrame both take rows first and columns second: df.loc[rows, columns].
  • Plain df[...] selects columns by name. On a Series, s[...] uses labels. Since pandas 3.0, an integer that is not a label raises KeyError; older versions quietly fell back to a position.
>>> s = pd.Series([0.92, 0.85, 0.95], index=["a", "b", "c"])
>>> s.loc["b"], s.iloc[1]
(np.float64(0.85), np.float64(0.85))
>>> s.loc["a":"b"].tolist(), s.iloc[0:1].tolist()
([0.92, 0.85], [0.92])
>>> s[1]
Traceback (most recent call last):
  ...
KeyError: 1

The mistake. Sorting and filtering keep the original labels. So after a sort, label 0 need not be the first row:

>>> df = pd.DataFrame({"run": ["a", "b", "c"], "loss": [0.58, 0.49, 0.80]})
>>> best = df.sort_values("loss")
>>> best
  run  loss
1   b  0.49
0   a  0.58
2   c  0.80
>>> best.loc[0, "run"], best.iloc[0]["run"]
('a', 'b')
>>> best.loc[0:1, "run"].tolist()
[]
>>> best.reset_index(drop=True).loc[0, "run"]
'b'

best.loc[0, "run"] is the run labelled 0, which is now second. Code that means "the first row" must say iloc. A label slice runs from one label to the other in the current order. Label 0 stands after label 1, so best.loc[0:1] is empty. reset_index(drop=True) numbers the rows from 0 again when the old labels mean nothing.

The index is a hash table from labels to positions, like the dict of the topic Dictionaries and sets. So loc with one label is a lookup, not a scan of all rows. A meaningful index, such as a run name or a date, is what makes alignment, joins and time series work.

Copy-on-Write

Selecting part of a table gives a new object. Does changing it change the original? In NumPy the answer was "it depends": a slice is a view, a mask gives a copy. pandas 3.0 replaced this with one rule.

The rule (Copy-on-Write). Any object derived from a DataFrame or Series, by indexing or by a method, behaves as a copy. Changing the derived object never changes the original. A DataFrame changes only through an assignment on that DataFrame itself: df.loc[rows, col] = value or df[col] = values.

A real copy of every selection would be slow. So the copy is lazy. The derived object shares the original's arrays, and data are copied only at the moment one of the two objects is written to.

>>> df = pd.DataFrame({"run": ["a", "b", "c"], "loss": [0.58, 0.49, 0.80],
...                    "epochs": [3, 3, 2]})
>>> short = df[df["epochs"] < 3]
>>> short["epochs"] = 10
>>> df["epochs"].tolist(), short["epochs"].tolist()
([3, 3, 2], [10])
>>> col = df["loss"]
>>> np.shares_memory(col.to_numpy(), df["loss"].to_numpy())
True
>>> col.iloc[0] = 0.0
>>> np.shares_memory(col.to_numpy(), df["loss"].to_numpy()), df["loss"].tolist()
(False, [0.58, 0.49, 0.8])

short is a filtered table, and setting its column changes short only. col starts out sharing the column's memory with df. The write col.iloc[0] = 0.0 makes pandas copy the data for col first, so df keeps its values and the two stop sharing.

What changed from pandas 2. Before 3.0, col.iloc[0] = 0.0 changed df through a view, and short["epochs"] = 10 raised the famous SettingWithCopyWarning. Whether you had a view depended on dtypes and on the kind of indexing. pandas 3.0 removed both the question and the warning.

Chained assignment never works. df["loss"][0] = 0.0 is two operations. df["loss"] builds a Series, and [0] = 0.0 writes into that Series, which behaves as a copy. pandas detects the pattern and warns:

>>> df["loss"][0] = 0.0
<python-input-10>:1: ChainedAssignmentError: A value is being set on a copy of a DataFrame or Series through chained assignment.
Such chained assignment never works to update the original DataFrame or Series, because the intermediate object on which we are setting values always behaves as a copy (due to Copy-on-Write).
...
>>> df["loss"].tolist()
[0.58, 0.49, 0.8]
>>> df.loc[0, "loss"] = 0.0
>>> df["loss"].tolist()
[0.0, 0.49, 0.8]

(The warning is trimmed; it goes on to suggest .loc.) ChainedAssignmentError is a warning, not an exception, so the program goes on with df unchanged. The fix is one indexing operation on df itself. It is the trap a[a > 6][0] = 99 from the topic NumPy arrays: there a[a > 6] was a real copy, and in pandas 3 every intermediate result behaves like one.

CSV, dtypes and missing values

Now the table from the topic Files and exceptions, grown to three runs, with one accuracy missing and a time for each epoch. This is metrics.csv:

run,epoch,loss,accuracy,time
a,1,0.92,0.61,2026-03-02 10:00
a,2,0.71,0.70,2026-03-02 10:30
a,3,0.58,0.76,2026-03-02 11:00
b,1,0.85,0.64,2026-03-02 12:00
b,2,0.66,,2026-03-02 12:40
b,3,0.49,0.79,2026-03-03 09:10
c,1,0.95,0.58,2026-03-03 10:00
c,2,0.80,0.66,2026-03-03 10:20

pd.read_csv takes a path or any file object. It reads column names from the header and infers each column's dtype from its text:

>>> m = pd.read_csv("metrics.csv", parse_dates=["time"])
>>> m.dtypes
run                    str
epoch                int64
loss               float64
accuracy           float64
time        datetime64[us]
dtype: object
>>> m["accuracy"].isna().sum(), m["accuracy"].mean(), m["accuracy"].count()
(np.int64(1), np.float64(0.6771428571428572), np.int64(7))
>>> (m["accuracy"] == np.nan).sum()
np.int64(0)
>>> m["time"].dt.hour.tolist()
[10, 10, 11, 12, 12, 9, 10, 10]

The empty field became NaN. Dates stay text unless they are named in parse_dates; then they become datetime64, here with microsecond resolution, and the .dt accessor gives their parts. Inference can be wrong for identifiers: a code 007 is read as the integer 7. Pass dtype={"code": "str"} for such columns, usecols to read only some columns, and na_values for your data's own "missing" markers.

The rule. The marker of a missing value depends on the column's dtype:

dtype missing value
float64 NaN
Int64, boolean (nullable, capital I) pd.NA
str (default for text since 3.0) NaN
datetime64 NaT, "not a time"
object (any Python objects, slow) None or NaN

isna() finds missing values whatever their marker. fillna(v) replaces them, and dropna() removes the rows that have them. Reductions skip them: sum ignores them, mean divides by the number of present values, and count counts the present ones. So the mean above is the mean of seven numbers.

>>> pd.Series([3, None, 2]).tolist()
[3.0, nan, 2.0]
>>> pd.Series([3, None, 2], dtype="Int64").tolist()
[3, <NA>, 2]
>>> pd.Series(["a", 1]).dtype
dtype('O')

NumPy's int64 has no spare bit pattern for "missing", so an integer column with a gap becomes float64. The nullable Int64 keeps a separate mask of missing positions and stays exact. A column that mixes text and numbers falls back to object, an array of pointers to Python objects, as slow as a list.

The mistake. NaN == NaN is False in floating point. So m[m["accuracy"] == np.nan] selects nothing, as the zero above shows. Test with isna().

Filtering and groupby

Filtering selects rows with a boolean Series. Combine conditions with & (and), | (or) and ~ (not), each condition in parentheses. The table m is the one read in the previous block:

>>> m[(m["epoch"] == 3) & (m["loss"] < 0.55)]
  run  epoch  loss  accuracy                time
5   b      3  0.49      0.79 2026-03-03 09:10:00
>>> m[m["run"].isin(["a", "c"]) & ~(m["epoch"] == 1)]["loss"].tolist()
[0.71, 0.58, 0.8]
>>> m[m["epoch"] == 3 & m["loss"] < 0.55]
Traceback (most recent call last):
  ...
TypeError: Cannot perform 'rand_' with a dtyped [float64] array and scalar of type [bool]

The parentheses are required: & binds tighter than == and <, so the last line first computes 3 & m["loss"]. The keywords and and or fail too. They ask for the truth value of a whole Series, which is ambiguous, and raise ValueError.

groupby. df.groupby(key)[column].agg(f) does three things:

  1. Split the rows into groups by the value of the key.
  2. Apply the function to the column within each group, one value per group.
  3. Combine the results into a Series indexed by the keys, sorted.
>>> m.groupby("run")["loss"].min()
run
a    0.58
b    0.49
c    0.80
Name: loss, dtype: float64
>>> m.groupby("run").agg(n=("epoch", "size"), scored=("accuracy", "count"),
...                      best=("loss", "min"), acc=("accuracy", "mean"))
     n  scored  best    acc
run
a    3       3  0.58  0.690
b    3       2  0.49  0.715
c    2       2  0.80  0.620

Named aggregation, name=(column, function), computes several summaries at once. size counts rows, count counts present values. Run b has three epochs but two scores, because one accuracy is missing. When two counts disagree, check for missing values first. transform returns one value per original row instead of one per group, so it can be compared with a column: m[m["loss"] == m.groupby("run")["loss"].transform("min")] keeps the best epoch of each run. Rows whose key is missing are dropped from the groups unless you pass dropna=False.

Why it is fast. pandas turns the key column into integer codes once. Then one compiled loop walks the codes and adds each value to its group's slot. For built-in reductions named by a string, such as "sum" or "mean", no Python code runs per row. A Python function, agg(lambda v: ...), runs once per group: fine for ten groups, slow for a million.

Time is a key too. With the dates as the index, resample groups rows by calendar periods:

>>> m.set_index("time")["loss"].resample("D").size()
time
2026-03-02    5
2026-03-03    3
Freq: D, Name: loss, dtype: int64

"D" means days, "W" weeks, "MS" months labelled by their first day. rolling(k).mean() gives a moving average over k rows, the usual way to smooth a noisy loss curve. Time zones, irregular sampling and lags are a subject of their own.

Merges and pivot tables

The run names say nothing about the model. That lives in another table, and merge joins the two by a key, like a join in SQL:

  • how="inner" (the default): only keys present in both tables;
  • how="left": every row of the left table, missing values where the right has no match;
  • how="outer": every key from either side.
>>> runs = pd.DataFrame({"run": ["a", "b", "d"], "model": ["mlp", "cnn", "cnn"],
...                      "lr": [0.01, 0.1, 0.01]})
>>> j = m.merge(runs, on="run", how="left")
>>> j[["run", "epoch", "loss", "model"]]
  run  epoch  loss model
0   a      1  0.92   mlp
1   a      2  0.71   mlp
2   a      3  0.58   mlp
3   b      1  0.85   cnn
4   b      2  0.66   cnn
5   b      3  0.49   cnn
6   c      1  0.95   NaN
7   c      2  0.80   NaN
>>> len(m.merge(runs, on="run")), len(m.merge(runs, on="run", how="outer"))
(6, 9)

Run c is not in runs. The left join keeps its two epochs with a missing model, and the inner join drops them. The outer join adds run d, which has no metrics.

The mistake. When a key appears twice on the right, each matching row on the left is repeated, once per match. Register run b twice, and its three epochs turn into six rows: a left merge of m with such a table has 11 rows instead of 8, and every sum computed afterwards is inflated. Pass validate="many_to_one": it raises MergeError ("Merge keys are not unique in right dataset") when the right-hand keys repeat. And compare row counts before and after every merge. df.join(other) is the same operation matched on the index.

Pivot tables. pivot_table is a groupby on two keys spread into a grid, one key along the rows and one along the columns. The loss of each run at each epoch:

>>> m.pivot_table(index="epoch", columns="run", values="loss")
run       a     b     c
epoch
1      0.92  0.85  0.95
2      0.71  0.66  0.80
3      0.58  0.49   NaN
>>> j.pivot_table(index="model", columns="epoch", values="loss", aggfunc="mean")
epoch     1     2     3
model
cnn    0.85  0.66  0.49
mlp    0.92  0.71  0.58

Run c stopped after two epochs, so its cell at epoch 3 is missing. The second table hides a trap: run c has no model, and a pivot drops missing keys just as groupby does. Its losses vanished without a word. Fill the key first, j["model"].fillna("unknown"), when every row must be counted. melt is the inverse of a pivot: it turns columns back into rows.

Row loops

Code that walks a table row by row, with iterrows or apply(f, axis=1), gives up the column storage that makes pandas fast. Take one computation, a loss times a batch size for every row, written five ways. On one laptop (Apple M1, pandas 3.1.0, best of three runs; your numbers will differ):

rows df["loss"] * df["batch"] zip over two columns itertuples() apply(f, axis=1) iterrows()
1 000 0.026 ms 0.12 ms 0.34 ms 2.9 ms 7.8 ms
100 000 0.085 ms 10 ms 27 ms 268 ms 777 ms

For 100 000 rows the column expression takes less than a tenth of a millisecond and iterrows most of a second, about 9000 times as long. The reason is the model of the first block. iterrows builds a new Series for every row: it collects a value from each column, finds a common dtype for them and makes an index, nearly 8 µs per row. apply(f, axis=1) builds the same Series and then calls f. itertuples builds a light named tuple instead, about thirty times cheaper. zip over two columns yields their values as Python numbers, cheaper still, but it is a Python loop, about 0.1 µs per row. The column expression is one NumPy multiplication.

The rule of thumb. Write the computation as operations on whole columns:

  • arithmetic and comparisons between columns;
  • np.where(cond, a, b) or s.where(cond, other) for "if … else";
  • the .str and .dt methods for text and dates;
  • groupby with built-in reductions, and merge instead of a lookup in a loop.

When a row loop is unavoidable, itertuples is the cheapest one. And measure before rewriting, as the topic Debugging and profiling taught: the slow loop is often not the one you suspect.

Leakage and what comes next

pandas cleans a whole table in one line. That is the trap when the table will later be split into training and test data. Fill missing values with the column mean, standardize a column, or encode a category by the mean of the target: done on the full table before the split, each of these computes a statistic from the test rows and writes it into the training rows. The model then sees information about the test set, and its test score is too optimistic. This is leakage.

The fix is the order: split first, compute every statistic on the training rows only, and apply the same values to the test rows. Below, a feature drifts upward over time, so the last 200 rows, the test set, are larger than the first 800:

rng = np.random.default_rng(0)
df = pd.DataFrame({"x": rng.normal(size=1000) + np.arange(1000) * 0.002})
df.loc[rng.choice(1000, size=100, replace=False), "x"] = np.nan
 
train, test = df.iloc[:800], df.iloc[800:]
fill = train["x"].mean()                  # training rows only
train["x"] = train["x"].fillna(fill)
test["x"] = test["x"].fillna(fill)
print(round(df["x"].mean(), 3), round(fill, 3))
print(train["x"].isna().sum(), test["x"].isna().sum(), df["x"].isna().sum())
0.946 0.776
0 0 100

A fill computed on the whole table would be 0.946: it has seen the test period. The training mean is 0.776. Under Copy-on-Write, train and test behave as copies, so filling them leaves df with its 100 gaps, and no .copy() or warning is needed. The same rule holds for groupby(...).transform("mean") of the target: compute it on the training rows. The course Machine Learning shows how far such leaks move a score, in the topic Data, features and leakage.

What this topic built: a DataFrame is named columns, each a typed array, sharing one row index; Series align on labels; loc takes labels and iloc positions; in pandas 3 a derived object behaves as a copy, and only one indexing operation on the frame itself changes it; missing values are NaN, pd.NA or NaT; groupby, merge and pivot_table replace the loops; column expressions beat row loops by thousands of times.

A table is not yet an answer. Do the losses still fall, which run is best, does the accuracy follow the loss? A figure shows this fastest. The pivot table of losses by epoch and run is already a set of loss curves, one column per run. The next topic, Plotting with Matplotlib, draws them.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.