01B.11 NumPy and pandas Essentials for AI Work
Call a chat model and you get back text. But everything around that call is numbers and tables: the embeddings you store and search, the eval results you score, the usage and cost logs you analyse, the CSVs of tickets and documents you clean before they ever reach a model. Two libraries do almost all of that work in Python: NumPy for fast maths on arrays of numbers, and pandas for labelled tables. This lesson teaches the parts of both that AI engineering actually uses — enough to read an embedding matrix, rank nearest neighbours, and answer "which model was cheapest per resolved ticket?" from a log file — and is deliberately honest about what it does not teach: no machine learning, no statistics, no plotting.
What you'll learn
- Why NumPy and pandas show up in AI work even though you never need them to call an LLM API — and the one-paragraph version of what this lesson leaves out
- NumPy arrays from first principles: creation,
dtype(why embeddings live infloat32),shape/ndim/axes, indexing and slicing, views versus copies, boolean masks and fancy indexing, reshaping and stacking - Broadcasting, reductions with
axis=, andargsort/argpartitionfor top-k retrieval - The linear algebra that powers semantic search: dot products,
@matrix multiplication, vector norms, cosine similarity, and the batch patternscores = matrix @ queryused by every vector store - Numerical hygiene for embeddings:
float32rounding,np.isclose,NaN, saving and loading arrays, and JSON interop - pandas from first principles:
SeriesandDataFrame, reading and writing CSV/JSON/JSONL/Parquet, flattening nested JSON records withjson_normalize, inspecting, selecting withloc/iloc/boolean filters/query, missing data, type conversion, the.straccessor,groupbyaggregation, merging and concatenating,pivot_table, sorting and method chaining,applyversus vectorized operations, datetimes, andread_sql - The pandas 3.x changes that break old habits: the
strdtype, Copy-on-Write semantics, chained assignment, and the deprecatedinplacekeyword - Four worked examples end to end: cosine-similarity search, an eval-results table, a usage-and-cost analysis, and cleaning a messy tickets CSV
- What the standard library does underneath (with real, runnable code), and when to reach for SQL, DuckDB or Polars instead
What you don't need
- Any machine-learning background. This lesson uses toy vectors you can check by hand; it does not train anything.
- Linear algebra beyond dot products and vector length, both of which are defined here in plain English.
- NumPy or pandas installed yet — the Setup section covers it — and no API key: nothing in this lesson calls a model.
- Statistics beyond means and counts. When a concept needs real statistics, the lesson links out instead of teaching it.
Setup
The samples need Python 3.11+ and the two libraries NumPy and pandas. They were written and checked against NumPy 2.5 and pandas 3.1 as of November 2026; pandas 3 is a recent major release that changed several defaults (such as the string dtype), so if you see output that differs from the lesson, print the installed versions (the check below) and read the release notes of the version you got. If you already have the module's aitoolkit project from 01B.1, add the packages to it:
uv add numpy pandas
# or, without uv: pip install numpy pandasParquet files need one more package; add it only when you reach 5.2:
uv add pyarrow # the Parquet engine pandas usesFirst time with uv? Create the project first: uv init data-playground --bare --python 3.13 && cd data-playground, then run the uv add commands above. Scripts run with uv run python file.py. No API key needed.
What you must be able to do after this lesson#
- Create NumPy arrays with the right dtype and shape
- Index and slice arrays and tell a view from a copy
- Compute dot products, norms and cosine similarity
- Rank results for top-k retrieval with matrix @ query and argpartition
- Load a CSV or JSONL file into a pandas DataFrame and filter and group it
- Explain when to use SQL, DuckDB or Polars instead
Why this matters for an AI engineer#
You can spend a year building LLM products without writing a neural network, but you cannot spend a week analysing their output without touching arrays and tables. The split is clean: NumPy owns the numbers (vectors, matrices, similarity scores) and pandas owns the labels (which document, which model, which day, which score).
| You'll hear... | You'll understand it after... |
|---|---|
"Store the embeddings as a float32 NumPy matrix." |
2.3 dtype |
"Why is arr[mask] = 0 silently doing nothing?" |
2.5 Views vs copies |
| "Broadcast the batch norms against the query." | 3.1 Broadcasting |
| "Score all 40k chunks against the query in one matmul." | 4.4 The retrieval pattern |
| "Cosine similarity, not dot product — the vectors aren't normalized." | 4.3 Cosine similarity |
| "Top-10 without sorting a million scores." | 3.3 argpartition |
"The eval CSV has N/A strings and blank priorities." |
6.4 Cleaning a messy CSV |
"SettingWithCopyWarning keeps firing." |
5.14 pandas 3.x — and why it no longer exists in pandas 3 |
| "Should this live in pandas or in SQL?" | 8.1 The decision table |
Part 1: Why these two libraries, and what this lesson is not#
1.1 The data around an LLM call#
Strip an LLM application down to its skeleton and the model call is a small part of it. Around the call sits a data pipeline:
flowchart LR
subgraph in ["Going in"]
A["Documents, tickets,<br/>CSV exports, logs"] --> B["Clean + chunk<br/>(pandas, 05.x)"]
B --> C["Embed<br/>(06.1-06.2)"]
end
subgraph core ["The model call"]
C --> D["LLM API<br/>(Modules 02-03)"]
D --> E["Text / JSON / stream"]
end
subgraph out ["Coming back"]
E --> F["Parse + validate<br/>(Pydantic, 01B.6)"]
F --> G["Store vectors<br/>+ metadata (06.x)"]
F --> H["Score + log<br/>results (10.x, 11.x)"]
end
G --> I["NumPy: similarity,<br/>top-k, batch maths"]
H --> J["pandas: eval tables,<br/>cost reports, pivots"]
I --> K["Decisions:<br/>retrieve, route, alert"]
J --> KNumPy enters at the vector end: an embedding is a list of a few hundred to a few thousand floats, and comparing two of them is a dot product over all of them. pandas enters at the table end: eval runs, cost logs and experiment results are rows and columns with names, dates and missing values. Both are glue libraries — they rarely touch the model itself, but they decide whether the data you feed it and the data you read back are trustworthy.
1.2 What this lesson deliberately does not cover#
It is worth being precise about the boundary, because "NumPy and pandas" is also the name of two enormous ecosystems:
| Not covered here | Where it lives instead |
|---|---|
Training models, autograd, tensors with gradients |
Out of scope for this path entirely — the path builds on models, it doesn't train them |
| Statistics (distributions, hypothesis tests, regression) | Link out when needed; this lesson uses means and counts only |
Plotting (matplotlib, seaborn, plotly) |
One paragraph of awareness in 8.3; visuals are not this lesson's job |
scikit-learn, torch, jax |
Their own ecosystems; this lesson gives you the array/table substrate they sit on |
| pandas' full API surface (hundreds of methods) | The 20% that covers 95% of AI-engineering work, plus the pointers to find the rest |
| Polars, DuckDB, Arrow, dask | Named and compared in 8.1; not taught |
1.3 Two shapes of data, two libraries#
The mental model for the whole lesson:
- A NumPy array (
ndarray) is a grid of same-typed numbers with a shape like(rows, columns)but no names. Fast because the numbers sit in one contiguous block of memory and operations run in compiled code, not the Python interpreter. - A pandas DataFrame is a table of columns with names, an index, mixed types per column, and missing-value semantics. Convenient because
df["score"]means something to a human.
Under the hood pandas uses NumPy arrays for its numeric columns — which is why df["emb"].to_numpy() hands you the array the vector maths wants. The two libraries are layers, not rivals.
Part 2: NumPy — the array at the centre of embeddings#
2.1 Why arrays at all#
A Python list of floats works fine for five numbers. It falls apart at five hundred thousand, which is the normal size of an embedding matrix (say 10,000 documents × 768 dimensions = 7.68 million floats). Two reasons:
- Memory layout. A Python list stores pointers to float objects; each float is a separate heap object.
[0.1, 0.2, 0.3]is roughly 100+ bytes of pointers plus three boxed floats. A NumPyfloat32array stores the numbers back-to-back: 4 bytes each, nothing else. The same 7.68 million floats take ~30 MB asfloat32instead of hundreds of MB as Python objects. - Speed of the operation, not just the storage.
sum(a * b for a, b in zip(x, y))executes Python bytecode once per element — millions of interpreter steps.np.dot(x, y)hands the whole loop to compiled C (often SIMD-vectorized, multi-threaded for large matrices). For the sizes embeddings live at, the difference is the gap between "wait a few seconds" and "wait minutes". The exact speedup depends on hardware and array size — typically one to two orders of magnitude for large 1-D dot products, more for big matrix multiplies — but the shape of the win is universal: the per-element Python overhead disappears.
2.2 Creating arrays#
# arrays.py — the constructors you'll actually use
import numpy as np
# From a nested list: shape is (rows, columns)
emb = np.array([[0.9, 0.1, 0.8],
[0.2, 0.7, 0.5]])
# Common factories
zeros = np.zeros((2, 3)) # 2x3 of 0.0
ones = np.ones(4) # four 1.0
ramp = np.arange(0, 10, 2) # [0, 2, 4, 6, 8] — like range(), but an array
lin = np.linspace(0, 1, 5) # five evenly spaced points 0..1
# Deterministic randomness — always seed, always use default_rng (not np.random.*)
rng = np.random.default_rng(seed=42)
noise = rng.standard_normal(3) # three draws from a standard normal>>> emb
array([[0.9, 0.1, 0.8],
[0.2, 0.7, 0.5]])
>>> ramp
array([0, 2, 4, 6, 8])
>>> lin
array([0. , 0.25, 0.5 , 0.75, 1. ])Two habits worth forming immediately:
np.random.default_rng(seed), not the legacynp.random.seed()/np.random.rand()API.default_rngis the modern, statistically better generator and gives you a localrngobject instead of mutating global state — so two parts of your program can have independent streams.np.arraycopies by default;np.asarraydoesn't. If you already have an array and just want it as an array,np.asarrayavoids a pointless copy. Thecopy=keyword exists too, with NumPy 2 semantics:copy=Falsemeans "never copy, raise if you must" —np.asarrayis the friendlier spelling of that intent.
2.3 dtype: why embeddings are float32#
Every array has a dtype — the data type of its elements. The ones you will meet constantly:
| dtype | Size | Typical use in AI work |
|---|---|---|
float64 |
8 bytes | NumPy's default for Python floats; the "safe" precision |
float32 |
4 bytes | The embedding dtype. Nearly every embedding API returns float32-ish precision; half the memory of float64, plenty for cosine similarity |
float16 |
2 bytes | Storage/transport for embeddings when memory is tight; check the precision trade-offs in 06.3 §1.5 |
int64 / int32 |
8 / 4 bytes | Token IDs, counts, indices. Note: NumPy 2.0 made the default integer 64-bit on all platforms, including Windows |
bool |
1 byte | Masks: array > 0.5 produces one |
str / bytes |
variable | Rarely useful in NumPy — this is pandas' job |
v = np.array([0.1, 0.2, 0.3])
print(v.dtype) # float64 — Python floats default to double
v32 = v.astype(np.float32) # the embedding dtype
print(v32.dtype, v32.itemsize) # float32 4
# astype always copies; view(dtype=...) reinterprets bits without copying
# (dangerous if you don't know what you're doing — see 2.5)Why float32 for embeddings: an embedding is already an approximation — the model produced it through lossy training and quantization. Chasing float64 precision on top of that buys nothing and doubles memory and bandwidth. Provider APIs return vectors you store and compare in float32; 06.3 works through exactly when float16 is safe to use instead.
2.4 shape, ndim and axes#
m = np.zeros((4, 3)) # 4 rows, 3 columns — a matrix of scores, say
print(m.shape, m.ndim) # (4, 3) 2
v = np.zeros(3)
print(v.shape, v.ndim) # (3,) 1 — note the trailing comma: 1-D, not a columnshapeis a tuple of dimension sizes:(4, 3)= 4 rows × 3 columns;(10, 768)= 10 embeddings of 768 numbers;(768,)= one embedding.ndimis the number of axes: 1 for a vector, 2 for a matrix, 3 for a batch of matrices, and so on.- An axis is one dimension of the array, numbered from 0.
axis=0is "down the rows" (across documents);axis=1is "across the columns" (across the embedding dimensions). Theaxis=argument on reductions and friends is where most beginners stumble — 3.2 makes it concrete.
2.5 Indexing and slicing: views vs copies#
m = np.arange(12).reshape(3, 4)
# m is:
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
m[0] # first row -> array([0, 1, 2, 3])
m[:, 1] # second column -> array([1, 5, 9])
m[1:, 2:] # rows 1-2, cols 2-3 -> array([[ 6, 7], [10, 11]])
m[-1] # last row (negative indexing works)The subtlety that bites everyone: basic slicing returns a view, not a copy. m[1:, 2:] does not duplicate data — it is a new array object that shares the same underlying memory with a different "window" onto it. Two consequences:
sub = m[:, 0]
sub[0] = 999
print(m[0, 0]) # 999 — you just edited m through the view!This is usually what you want (zero-copy speed), but it means a "subset" can silently mutate the original. The rule of thumb:
- Basic slices (
a[1:3],a[:, ::2]) → view when possible. - Anything that gathers by position or mask — integer lists (
a[[0, 2]]), boolean masks (a[mask]) — → copy. Operations that only re-describe the same memory stay views:a.T/transpose,np.flipandreshape(when the memory layout allows it; otherwisereshapequietly copies). Check.base(a.base is Nonemeans the array owns its data) ornp.shares_memory(a, b)if it matters. - When you need independence:
arr.copy()ornp.array(arr)(which copies by default).
One asymmetry worth memorizing: a[mask] on the right-hand side reads a copy, but a[mask] = v on the left-hand side writes straight into a — boolean masks are for filtering reads and for deliberate in-place masked assignment (2.6), never for making an independent subset.
Fancy indexing — indexing with a list or array of integers or booleans — always copies:
m[[0, 2]] # rows 0 and 2 — a copy
m[m[:, 0] > 4] # rows whose first column exceeds 4 — boolean mask, also a copy2.6 Boolean masks and fancy indexing#
Boolean masks are the workhorse of array filtering — "give me the rows where score > 0.8":
scores = np.array([0.91, 0.44, 0.87, 0.62, 0.95])
labels = np.array(["refund", "bug", "billing", "refund", "feature"])
scores > 0.8 # array([ True, False, True, False, True])
scores[scores > 0.8] # array([0.91, 0.87, 0.95]) — filtered copy
labels[scores > 0.8] # array(['refund', 'billing', 'feature'], dtype='<U7')
# You can also assign through a mask
scores[scores < 0.5] = 0.0 # clamp the low score in placeFancy indexing with integer arrays selects by position:
top3 = np.argsort(scores)[-3:] # positions of the 3 largest, ascending
scores[top3] # their valuesNote argsort returns positions, sort returns values — memorize which is which now; 3.3 builds the whole top-k pattern on it.
2.7 Reshaping, stacking and concatenating#
flat = np.arange(6)
mat = flat.reshape(2, 3) # view when possible — shares memory
mat.T # transpose — a view
# Building bigger arrays from pieces
np.concatenate([a, b], axis=0) # glue along rows (axis=0)
np.stack([v1, v2, v3]) # NEW leading axis: 3 vectors -> (3, d) matrix
np.vstack([a, b]) # stack as rows == concatenate on axis 0 for 2-D
np.hstack([a, b]) # stack as columnsreshape/T/transpose return views (free); concatenate/stack allocate new memory (necessary — the result genuinely has more elements). np.stack is the one you'll use constantly: a list of per-document embedding vectors becomes the (n_docs, dim) matrix by np.stack(vectors).
Part 3: Broadcasting, reductions and sorting#
3.1 Broadcasting: the rule and a diagram#
Broadcasting is NumPy's answer to "my arrays have different shapes — can I still operate on them together?" The rule, in one sentence: dimensions are aligned from the right, and a dimension of size 1 (or a missing trailing dimension) stretches to match.
q = np.array([1.0, 2.0, 3.0]) # shape (3,)
m = np.zeros((4, 3)) # shape (4, 3)
m + q
# Align from the right:
# m: (4, 3)
# q: (3,) -> treated as (1, 3), then stretched to (4, 3)
# Result: (4, 3) — q added to every rowThe same rule, drawn:
flowchart TB
subgraph shapes ["Shapes line up from the RIGHT"]
A["matrix (4, 3)"] --> R["result (4, 3)"]
B["vector (3,)"] --> R
C["scalar ()"] --> R
end
subgraph stretch ["Size-1 dims stretch; others must match or be 1"]
D["(4, 1) column"] --> R2["with (3,) -> (4, 3)"]
E["(1, 3) row"] --> R2
endBroadcasting is how you subtract a per-document mean from a matrix, add a bias vector to every row, or scale each column differently — without writing a single loop. In embedding work it shows up constantly: normalize every row of a (n, d) matrix by dividing by a (n, 1) column of norms.
The errors are loud, thankfully: np.zeros((4, 3)) + np.zeros(4) raises ValueError: operands could not be broadcast together with shapes (4,3) (4,) — because (4,) aligns with the last axis (size 3), not the rows. When broadcasting fails, ask "which axis did I mean?" and add the missing [:, None]/[None, :] to make it explicit.
3.2 Reductions and the axis argument#
A reduction collapses an array along one or more axes to a smaller array (or scalar):
m = np.arange(12).reshape(3, 4)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
m.sum() # 66 — everything
m.sum(axis=0) # [12 15 18 21] — down the rows: one value per COLUMN
m.sum(axis=1) # [ 6 22 38] — across columns: one value per ROW
m.mean(axis=1) # row means
m.max(axis=0) # per-column max
m.argmax(axis=1) # index of the max within each rowThe mnemonic: axis=k means "collapse axis k" — the result has one fewer dimension, and the surviving axes keep their order. axis=0 on a (docs, dims) matrix summarizes per embedding dimension; axis=1 summarizes per document. Getting this backwards is the single most common NumPy bug in real code — when a result "looks transposed", check the axis.
np.linalg.norm(m, axis=1) gives per-row lengths — the norms you need for cosine similarity in 4.3.
3.3 Sorting and top-k: argsort and argpartition#
scores = np.array([0.31, 0.87, 0.44, 0.91, 0.62])
scores.argsort() # positions that would sort ascending: [0 2 4 1 3]
scores.argsort()[::-1] # descending positions: [3 1 4 2 0]
scores.argsort()[-3:] # positions of top-3, ascending order
scores[scores.argsort()[-3:][::-1]] # values, best firstFor "the k best", argsort sorts everything — fine for hundreds of items, wasteful for a million. argpartition does a partial selection: it guarantees the top-k are in the first k slots without sorting the rest:
k = 3
idx = np.argpartition(-scores, k - 1)[:k] # positions of k largest (unordered)
best = idx[np.argsort(-scores[idx])] # then sort just those kThis is exactly the pattern vector stores use for exact k-NN over a flat index — 06.3 §1.3 builds on it, and 06.5 ships a pure-NumPy in-memory store doing precisely this.
Part 4: The maths that matters for embeddings#
This part is the payoff: the handful of operations that turn "a pile of vectors" into "semantic search". Everything here is ordinary arithmetic — the only new idea is that a vector's direction encodes meaning, so similarity is measured by angle, not distance.
4.1 Dot product and matrix multiplication#
The dot product of two equal-length vectors multiplies matching entries and sums:
[1, 2, 3] · [4, 5, 6] = 1*4 + 2*5 + 3*6 = 32x = np.array([1.0, 2.0, 3.0])
y = np.array([4.0, 5.0, 6.0])
x @ y # 32.0 — the @ operator is dot product for 1-D, matmul generally
np.dot(x, y) # same thing, explicit
np.vecdot(x, y) # NumPy 2.0+: batched/vectorized variant for stacks of vectors
np.outer(x, y) # every x_i * y_j — a (3,3) matrix of pairwise productsFor 2-D arrays, @ is matrix multiplication: (n, k) @ (k, m) -> (n, m), where each output cell is a dot product. This is the operation GPUs were built for, and it is why "embeddings are just matrix multiplication" is the correct mental model: scoring a query against a document matrix is one @.
4.2 Vector norms#
The norm (length, magnitude) of a vector is sqrt(sum of squares):
v = np.array([3.0, 4.0])
np.linalg.norm(v) # 5.0 — the classic 3-4-5 triangle
# For a matrix of row vectors: one norm per row (axis=1 keeps dims)
M = np.array([[3.0, 4.0], [0.0, 2.0]])
np.linalg.norm(M, axis=1) # array([5., 2.])Dividing a vector by its norm gives a unit vector — length 1, direction preserved. Unit vectors are what make cosine similarity cheap: for unit vectors, dot product is cosine similarity.
4.3 Cosine similarity#
Cosine similarity measures the angle between two vectors, ignoring their length:
cosine(a, b) = (a · b) / (||a|| × ||b||) range: -1 to +1Identical direction → 1.0; orthogonal → 0.0; opposite → -1.0. For embeddings — where "length" is mostly a confidence/scale artefact and "direction" is the meaning — cosine is the default metric. 02.3 §4 derives it and compares it with dot product and Euclidean distance; 06.3 covers the score/distance conventions every library uses.
def cosine(a: np.ndarray, b: np.ndarray) -> float:
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))Two production notes:
- Normalize once, dot forever. If you store embeddings already unit-normalized (
v / np.linalg.norm(v)at index time), then cosine similarity is the dot product — you can skip the norms at query time entirely. This is what every vector DB does internally, and 06.1 §1.3 explains why some providers normalize for you and some don't. np.isclose, not==. Float arithmetic is not exact:0.1 + 0.2 == 0.3isFalsein floating point. Compare withnp.isclose(a, b)(ormath.isclose) when checking similarity scores or reconstructed values — the lesson's 4.5 shows where this bites.
4.4 The pattern that powers vector search#
Here is the whole trick behind "find the k most similar documents", in five lines:
# docs: (n_docs, dim) matrix of unit-normalized embeddings
# query: (dim,) unit-normalized vector
scores = docs @ query # (n_docs,) — one dot product per doc, in C
k = 10
top = np.argpartition(-scores, k - 1)[:k] # k best positions, unordered
top = top[np.argsort(-scores[top])] # order just those k, best firstscores[i] is the cosine similarity between document i and the query. One matrix-vector product replaces n_docs Python-level dot products. For 40,000 × 768 floats this is ~30M multiply-adds — milliseconds on a modern CPU, microseconds-to-milliseconds on a GPU. 06.3 §1.4 benchmarks this exact pattern and works out when brute force stops being fast enough (the answer involves ANN indexes, which are Module 06's subject — not this lesson's).
4.5 Numerical issues: float32 rounding, NaN and isclose#
Embeddings are floats, and floats lie a little:
float32has ~7 significant decimal digits. A cosine similarity computed infloat32might give0.99999994wherefloat64gives1.0. Never assert exact equality on floats — usenp.isclose.NaNpoisons everything. A singleNaNin a vector makes every dot product touching itNaN, and NumPy's sorting putsNaNlast, so the affected documents quietly drop out of a best-first ranking instead of raising an error. Check withnp.isnan(arr).any()ornp.isfiniteafter loading embeddings from disk or APIs — a truncated JSON line or a provider glitch produces exactly this.- Overflow/underflow are rare but real in unnormalized dot products of large vectors; normalizing first (unit vectors) keeps scores in a sane range.
- Dtype mixing: mixing
float32arrays with Python floats under NEP 50 promotion (NumPy 2.0+) keepsfloat32precision — usually what you want, occasionally a surprise if you expectedfloat64. When in doubt,astypeexplicitly.
4.6 Saving, loading and JSON#
np.save("emb.npy", matrix) # one array -> .npy file
loaded = np.load("emb.npy") # allow_pickle=False by default: safe
np.savez("batch.npz", docs=matrix,
meta=np.arange(matrix.shape[0])) # many arrays -> one .npz (zip)
z = np.load("batch.npz")
z["docs"], z["meta"]
# Memory-map a huge .npy instead of loading it all — essential at 10M+ vectors
mm = np.load("huge.npy", mmap_mode="r") # reads lazily from diskallow_pickle=False is the default since NumPy 1.16.3 — never pass allow_pickle=True on files you didn't write yourself; pickled arrays can execute arbitrary code on load (same reason 02.1 §4.7 warns about .bin weight files).
For JSON: arr.tolist() converts to nested Python lists (what json.dumps wants); np.array(list_of_lists) comes back. Embedding APIs return JSON arrays of floats — np.asarray(response.data[0].embedding, dtype=np.float32) is the standard ingest line.
Part 5: pandas — tables with labels#
NumPy arrays are fast because they are unlabelled: position is everything. Real data is labelled — "the score column", "rows where model == 'gpt-6-luna'", "the created_at date". pandas is the library that keeps the labels attached to the numbers.
5.1 Series and DataFrame#
Two objects carry everything:
- A
Seriesis a one-column table: an array of values plus an index of labels (by default0, 1, 2, ...). - A
DataFrameis a table of named columns, each aSeries, all sharing one index.
# frames.py — building a small eval-results table from scratch
import pandas as pd
df = pd.DataFrame({
"prompt_id": ["p01", "p02", "p03", "p04"],
"model": ["gpt-6-luna", "gpt-6-luna", "claude-haiku-5-5", "claude-haiku-5-5"],
"score": [0.91, 0.76, 0.88, 0.54],
"passed": [True, True, True, False],
})
print(df)
print(df.dtypes) prompt_id model score passed
0 p01 gpt-6-luna 0.91 True
1 p02 gpt-6-luna 0.76 True
2 p03 claude-haiku-5-5 0.88 True
3 p04 claude-haiku-5-5 0.54 False
prompt_id str
model str
score float64
passed bool
dtype: objectNote the str dtype on the text columns — pandas 3 infers a dedicated str dtype for text columns (more on that in 5.14). The index 0..3 is just labels; it is not "the row number" in any deeper sense, which matters for joins later.
5.2 Reading and writing: CSV, JSON/JSONL and Parquet#
# io.py
df = pd.read_csv("eval_results.csv")
df.to_csv("eval_results_clean.csv", index=False) # index=False: don't write the index as a column
# JSONL — one JSON object per line — is the format LLM logs and eval sets use
events = pd.read_json("runs.jsonl", lines=True)
events.to_json("runs_out.jsonl", orient="records", lines=True)
# Parquet — columnar, typed, compressed; the right format for datasets at scale
# needs: uv add pyarrow
df.to_parquet("eval_results.parquet", index=False)
df2 = pd.read_parquet("eval_results.parquet")LLM logs rarely arrive flat. A provider response or trace record nests the interesting numbers ({"model": ..., "usage": {"input_tokens": ..., "output_tokens": ...}}), and a DataFrame with a dict in a cell is hard to analyse. pd.json_normalize flattens a list of such records into columns, joining nested keys with a separator:
# nested.py — flatten nested log records into a table
import pandas as pd
records = [
{"id": "r1", "model": "gpt-6-luna", "usage": {"input_tokens": 120, "output_tokens": 35}},
{"id": "r2", "model": "claude-haiku-5-5", "usage": {"input_tokens": 98, "output_tokens": 41}},
]
flat = pd.json_normalize(records) # sep="." by default
print(flat.columns.tolist())['id', 'model', 'usage.input_tokens', 'usage.output_tokens'](A dotted column name selects normally with df["usage.input_tokens"], but inside query() it needs backticks; sep="_" avoids the dots altogether.) Lists nested inside a record stay as list cells; df.explode("column") turns one row per list item when you need that.
The practical differences that matter for AI work:
| Format | Best for | Watch out for |
|---|---|---|
| CSV | Human-readable exports, quick exchanges | No types — everything is text; dates and NA need parsing; slow on huge files (though pandas 3.1 reads large local CSVs in parallel by default — 5.14) |
| JSON / JSONL | API responses, streaming logs, eval fixtures | read_json needs lines=True for JSONL; nested objects land as dicts/lists |
| Parquet | Datasets you will analyse repeatedly | Needs pyarrow (or fastparquet); preserves dtypes; not human-readable |
SQL (via read_sql) |
Data already in a database | See 5.13 |
5.3 Inspecting a DataFrame#
Before analysing, look:
df.head(3) # first rows — the 80% inspection tool
df.info() # rows, columns, non-null counts, dtypes — memory too
df.describe() # count/mean/std/min/25%/50%/75%/max for numeric columns
df.shape # (rows, columns)
df.columns.tolist() # the labelsinfo() is the one to run first on any real file: it tells you the row count, which columns have missing values, and the dtype pandas actually inferred — the three things that decide whether the rest of your analysis is sound.
5.4 Selecting data: [], loc, iloc, masks and query#
# frames_select.py — df is the eval table from 5.1
df["score"] # one column -> Series
df[["prompt_id", "score"]] # several columns -> DataFrame
df.loc[0] # row labelled 0 -> Series
df.loc[0, "score"] # one cell -> scalar
# Boolean masks — the workhorse
df[df["score"] > 0.8] # rows where score > 0.8
df.loc[df["model"] == "gpt-6-luna"] # same thing, explicit .loc
df[df["passed"] == False] # failures only
# iloc is positional — ignore the index labels entirely
df.iloc[0] # first row
df.iloc[:3, 1:3] # first 3 rows, columns 1-2 by position
# query() reads like a filter expression
df.query("score > 0.8 and model == 'gpt-6-luna'")The rules to keep straight:
df["col"]selects a column;df.loc[row_label]selects a row.df[0]does not mean "the first row": it looks for a column labelled0and raisesKeyErrorwhen the columns are named (as in our eval table). Use.loc[label]or.iloc[position]for rows..locis label-based (the index),.ilocis position-based (0= first row regardless of label). Mixing them up is the classic pandas bug —df.loc[0]afterdf = df.sort_values("score")is no longer "the first row".- Boolean masks align on the index —
df[df["score"] > 0.8]works because both sides share the index. If you build a mask from a different frame or a NumPy array of the wrong length, pandas raises or misaligns silently; see 5.14 on alignment. query()is convenient but has limits: column names with spaces or dots need backticks (df.query("`cost usd` > 1")), and it can't see local variables unless you pass them — for anything non-trivial, the explicit maskdf[df["score"] > 0.8]is clearer anyway.
New columns are assignments:
df["score_pct"] = df["score"] * 100 # vectorized — whole column at once
df = df.assign(verdict=lambda d: d["passed"].map({True: "pass", False: "fail"})) # or assign()Prefer df["new"] = ... and df.assign(...) over mutating in place when chaining — under Copy-on-Write (5.14) chained assignment is the trap to avoid. 5.16 covers the fluent chain style properly.
5.5 Missing data#
Real AI data is full of holes: a log row with no cost, an eval with an unparseable score, a CSV cell that says N/A. pandas represents missing values as NaN (float columns), NaT (datetimes) or NA (nullable dtypes) — and None in object columns is usually treated as missing too.
s = pd.Series([0.9, None, 0.7, float("nan")])
s.isna() # which are missing — always use isna(), never `== None` or `is None`
s.isna().sum() # count of missing
s.fillna(0.0) # replace missing with a value — returns a NEW series
s.dropna() # drop missing rows — also returns new
s.ffill() # propagate the last real value forward (time series)
s.bfill() # ...or backward
s.notna() # the inverse mask, for keeping good rowsRules of thumb:
- Decide deliberately, don't default.
fillna(0)on a score column invents data — a missing eval score is not a zero.dropna()shrinks your dataset silently; log how many rows you dropped.s.ffill()propagates the last real value forward — right for time series, wrong for scores. (The oldfillna(method="ffill")spelling was removed in pandas 3.0 — it now raisesTypeError; same story formethod=/limit=onreplace().) isna()covers all three sentinels (NaN,NA,NaT,Nonein most contexts).pd.isna(x)works on scalars too.- In pandas 3 the default string dtype uses
NaNas its missing sentinel (notpd.NA) — see 5.14 for why that matters when checkingdtype == object.
5.6 Types and conversions#
df["score"].astype(int) # float -> int (truncates! check first)
df["score"].astype("float32") # narrower float — halves memory
df["tokens"].astype("Int64") # nullable integer — keeps NA as NA, not NaN
pd.to_numeric(df["score"], errors="coerce") # bad values -> NaN instead of raising
pd.to_datetime(df["created_at"]) # strings -> datetime64
pd.to_datetime(df["created_at"], errors="coerce", utc=True) # + unparseable -> NaTto_numeric(..., errors="coerce")is the cleaning workhorse: "123" → 123, "N/A" →NaN, no exception. Follow it withisna().sum()to count what got coerced — silent coercion hides data problems.Int64(capital I) is the nullable integer dtype — it can holdNAproperly. Plainint64cannot represent missing, so pandas silently upcasts a column with a missing value tofloat64(and1becomes1.0). If integer columns matter (IDs, counts), useInt64.to_datetimeparses many formats; passformat=when the format is known and consistent (faster and stricter),utc=Truewhen mixing timezones — pandas 3 represents timezones withzoneinforather thanpytzby default.
5.7 Strings: the .str accessor#
Text columns get vectorized string methods through .str — no Python loop needed:
df["model"].str.lower() # case-fold whole column
df["model"].str.contains("haiku") # boolean mask of matches
df["model"].str.startswith("gpt")
df["prompt_id"].str.replace("p", "prompt-", regex=False)
df["text"].str.len() # character counts
df["text"].str.split(" ").str[0] # first word of each.str.contains returns a boolean Series you can use directly as a mask: df[df["model"].str.contains("haiku")]. For regex, .str.contains(pat, regex=True); for literal substring matching prefer regex=False (or escape the pattern) — unescaped ./+ in a "literal" search is a classic bug.
5.8 groupby and aggregation#
The split-apply-combine pattern: split rows by a key, compute something per group, stitch results back.
# eval_results: prompt_id, model, score, passed
df.groupby("model")["score"].mean() # mean score per model
df.groupby("model")["score"].agg(["mean", "count", "std"])
df.groupby("model")["passed"].sum() # passes per model (True=1)
df.groupby("model").size() # rows per model
df["model"].value_counts() # same as groupby().size() on one col
df.groupby(["model", "prompt_id"])["score"].first() # multi-key groupingagg/aggregate takes a list of function names or callables: .agg(["mean", "max", lambda s: s.quantile(0.9)]). For "average plus how many", .agg(mean_score=("score", "mean"), n=("score", "size")) names the output columns — the named-aggregation syntax is worth learning; it produces tidy summary tables directly.
5.9 Combining: merge, join and concat#
# merge = SQL JOIN on keys
evals = pd.merge(results, prompts_meta, on="prompt_id", how="left")
# how: "inner" (both sides), "left" (keep all left rows), "right", "outer"
# concat = stacking rows (axis=0) or columns (axis=1)
all_runs = pd.concat([run_oct, run_nov], ignore_index=True)
wide = pd.concat([scores_a, scores_b], axis=1)mergealigns on key columns, exactly like a SQL join — including the trap: duplicate keys on either side produce a cartesian explosion of rows. Checkdf.duplicated("key").sum()before merging if row counts matter.joinismergespecialized to the index; you will meet it in older code, butmergecovers the same ground more explicitly.concat(axis=0)is "append these tables" — useignore_index=Trueunless the indexes are meaningful, or you'll get duplicate index labels that break later.loclookups.- When combining tables that came from different files, check the key dtypes and formats match. A text key against an integer key (
"42"vs42) will not join: pandas usually refuses loudly withValueError: You are trying to merge on ... and int64 columns. The quiet failure is two text keys that look alike but differ ("042"vs"42", a trailing space, different case): nothing matches, and ahow="left"merge fills the right-hand columns withNaN. This is the #1 real-world merge bug — normalize both sides deliberately, and count the unmatched rows after a left join (merged["col"].isna().sum()).
5.10 Reshaping: pivot_table and melt#
# Long -> wide: one row per (model, prompt), score as the value
pivot = df.pivot_table(index="prompt_id", columns="model",
values="score", aggfunc="mean")
# pivot looks like:
# model claude-haiku-5-5 gpt-6-luna
# prompt_id
# p01 0.88 0.91
# p02 0.54 0.76
# ...
# Wide -> long: the inverse
df_long = pivot.reset_index().melt(id_vars="prompt_id",
var_name="model", value_name="score")pivot_table is GROUP BY + spread-into-columns in one call; aggfunc controls duplicates (default "mean" — pass "first" or a list if you want different behaviour). melt unpivots: every non-id_vars column becomes a row. Most eval analysis is "pivot scores by model, compare columns" — this is the operation.
5.11 apply versus vectorized operations#
df["text"].str.upper() # vectorized: C-level loop, fast
df["text"].apply(str.upper) # Python-level loop: calls str.upper per row, slowThe rule: if a vectorized method exists (.str, arithmetic on columns, .dt, comparison ops), use it. .apply runs a Python function once per row — fine for a few hundred rows, painful at a million, and it returns whatever the function returns so dtype inference can surprise you. .map on a Series is the same idea for value lookup (s.map({"a": 1}) or s.map(func)). Reach for apply only when no vectorized equivalent exists — and when you do, consider whether the operation belongs in NumPy or plain Python instead.
5.12 Datetimes#
df["created_at"] = pd.to_datetime(df["created_at"], utc=True)
df["created_at"].dt.date # date part
df["created_at"].dt.hour # hour part
df["created_at"].dt.day_name() # "Monday" ...
df.set_index("created_at").resample("1D")["cost"].sum() # daily totals
df["created_at"] - pd.Timestamp("2026-10-01", tz="UTC") # timedeltas.dt is the datetime accessor — same idea as .str for strings. resample is GROUP BY for time: it bins a datetime index into intervals ("1D", "1h", "W") and aggregates — the standard way to get "cost per day" from a timestamped log. Timezone-aware timestamps (utc=True at parse time) prevent the silent-local-time bugs that wreck cross-region cost reports.
5.13 Reading from SQL: read_sql with sqlite3#
If the data already lives in a database, don't export to CSV first — pandas reads SQL directly:
# read_sql.py — needs only the stdlib sqlite3 module
import sqlite3
import pandas as pd
conn = sqlite3.connect("tickets.db")
df = pd.read_sql("SELECT id, priority, created_at FROM tickets", conn)
df.head()
conn.close()This is the bridge between Module 00's SQL basics and pandas: SQL for storage and server-side filtering (WHERE, JOIN, GROUP BY at the database), pandas for the in-memory reshaping SQL is awkward at. The judgement call — when to filter in SQL versus pull everything and filter in pandas — is exactly 8.1's decision table. For anything beyond SQLite, read_sql works with SQLAlchemy connections or DBAPI2 drivers (psycopg for Postgres).
5.14 pandas 3 changes: Copy-on-Write and friends#
pandas 3.0 (January 2026) made two changes that break old habits — know them before you copy code from a 2024 tutorial:
1. Copy-on-Write is the only semantics. Every selection or method that returns a DataFrame/Series now behaves as a copy: modifying it never touches the original, and pandas only copies memory when it actually has to. Consequences:
- Chained assignment is dead.
df[df["score"] > 0.8]["passed"] = Trueused to sometimes work (with aSettingWithCopyWarning); in pandas 3 it never works — the first step returns something that behaves as a copy, so the assignment lands on a temporary anddfis untouched.SettingWithCopyWarningis gone (the class is absent frompandas.errorsin the 3.0.0 source); its replacement is aChainedAssignmentErrorwarning (pandas.errors.ChainedAssignmentError, present in the 3.0.0 and 3.1.0 sources and documented in the pandas 3.1 API reference as the warning raised when setting through chained assignment; filterable withwarnings.filterwarnings). Treat it as a bug report on your own code: the line it points at does nothing to the original frame, whether or not you ever see the warning. The fix is always one step:mask = df["score"] > 0.8; df.loc[mask, "passed"] = True. inplace=is deprecated (pandas 3.1).df.dropna(inplace=True)still runs but warns; writedf = df.dropna().- Defensive
.copy()calls added to silenceSettingWithCopyWarningare no longer needed — but an explicit.copy()is still correct when you genuinely want an independent snapshot.
2. The str dtype is the default for text. String columns now get a dedicated str dtype (backed by PyArrow when installed, else NumPy object under the hood) instead of object. Consequences:
df["col"].dtype == objectchecks break — the dtype is nowstr.- The missing-value sentinel for strings is
NaN, consistent with float columns. df["col"].str.*methods work the same; string ops are faster with PyArrow installed.
Other pandas 3 changes worth knowing: timezones use zoneinfo instead of pytz; concat no longer ignores sort for DatetimeIndex; read_csv on large local files reads in parallel by default (mode.max_threads defaults to CPU count capped at 6 — set it to 1 inside already-parallel apps); Timedelta.total_seconds includes nanoseconds. The full list is in the pandas 3.0.0 and 3.1.0 release notes — check them when upgrading older code.
5.15 Performance and memory#
pandas is not free. The habits that keep it fast at AI-data scale:
- Column dtypes are memory.
object/strcolumns are the expensive ones;categorydtype for low-cardinality text (model names, statuses, labels) stores each distinct value once — amodelcolumn with 3 values repeated a million times shrinks dramatically:df["model"] = df["model"].astype("category"). - Read only what you need.
pd.read_csv(..., usecols=[...]),dtype={...}, andnrows=/chunksize=for huge files —chunksizegives you an iterator of DataFrames so you never hold the whole file in memory. - Vectorized >
apply> Python loops, in that order (see 5.11). - Know the ceiling. pandas is single-machine, in-memory. When a file outgrows RAM — multi-GB logs, hundreds of millions of rows — the answer is SQL (push the work to the database), DuckDB (analytical SQL over files, see 8.1), Polars (lazy, multi-threaded dataframe engine), or chunked processing. pandas is the right tool for "data that fits in memory and needs labels" — which covers most eval and cost analysis.
5.16 Sorting and method chaining#
Two operations every analysis ends with: putting rows in order, and composing the steps into one readable expression.
Sorting comes in two flavours — by data or by label:
| Call | Orders by | Reach for it when |
|---|---|---|
df.sort_values("score", ascending=False) |
the values in a column | ranking rows — "top scores first" is the everyday case |
df.sort_index(ascending=False) |
the index labels themselves | the index carries meaning (timestamps, IDs), or you want the pre-sort order back |
sort_values options that matter: na_position="first"|"last" (missing values sort last by default), ignore_index=True when the old labels should not travel with the rows, and kind="stable" when rows that compare equal must keep their incoming order (the default is quicksort, which does not guarantee that; sorts on multiple columns always use the stable path). sort_index takes the same ascending/na_position/kind/ignore_index options, and Series.sort_values/Series.sort_index behave identically on one column. Sorting returns a new frame — the inplace= spelling is deprecated in pandas 3.1, so write df = df.sort_values(...), never df.sort_values(..., inplace=True).
Method chaining is the fluent style that falls out of "every operation returns a new frame":
# chains.py — top-5 gpt-6-luna prompts, as one expression
top = (df[df["model"] == "gpt-6-luna"]
.sort_values("score", ascending=False)
.head(5)
.reset_index(drop=True))Each call hands its result to the next — filter, sort, truncate, tidy — and under Copy-on-Write (5.14) no step can mutate a frame another step is still reading. When a step needs the whole frame rather than a column expression, df.pipe(func) slots a function into the chain. The trade-off is readability: chains of two or three obvious steps are great; once you need a comment or a debug print inside, give the intermediate a name (filtered = ...) — a named variable is cheaper than a mystery.
Part 6: Four worked examples, end to end#
Everything above was a fragment. Here are the four jobs this lesson exists for, each as a complete script you could adapt tomorrow. The input CSVs are shown in full so every example actually runs. Every output here is labelled illustrative, because exact formatting depends on your NumPy and pandas versions; the numbers themselves are checkable by hand, and Part 7 reproduces them with the standard library alone.
6.1 Cosine-similarity search over five toy vectors#
Five "documents" as hand-made 4-dimensional vectors (toy embeddings — real ones come from an embedding API and have hundreds of dimensions, but the maths is identical), one query, ranked by cosine similarity:
# semantic_search.py — the whole retrieval loop, toy-sized
import numpy as np
# Toy "embeddings": invented 4-D vectors standing in for real ones.
# Columns are arbitrary; what matters is that similar docs point the same way.
docs = np.array([
[0.90, 0.10, 0.80, 0.20], # d1 budget-laptop-deals
[0.70, 0.90, 0.10, 0.80], # d2 enterprise-server-pricing
[0.80, 0.30, 0.60, 0.40], # d3 student-discount-guide
[0.20, 0.70, 0.50, 0.90], # d4 luxury-watch-review
[0.50, 0.20, 0.40, 0.70], # d5 warranty-returns-policy
], dtype=np.float32)
names = ["budget-laptop-deals", "enterprise-server-pricing",
"student-discount-guide", "luxury-watch-review",
"warranty-returns-policy"]
query = np.array([0.85, 0.15, 0.70, 0.30], dtype=np.float32) # "cheap laptop for students"
# Normalize once — then cosine IS the dot product
docs_n = docs / np.linalg.norm(docs, axis=1, keepdims=True)
q_n = query / np.linalg.norm(query)
scores = docs_n @ q_n # (5,) cosine similarities
top = np.argsort(-scores) # all 5, best first (tiny data: full sort fine)
for i in top:
print(f"{scores[i]:.4f} {names[i]}")0.9931 budget-laptop-deals
0.9829 student-discount-guide
0.8468 warranty-returns-policy
0.6470 enterprise-server-pricing
0.6166 luxury-watch-reviewThe ranking is correct: the two documents about cheap student tech win, the luxury watch loses. Part 7 runs the identical computation in pure Python so you can verify the numbers by hand. At real scale docs is (40000, 768) and this same code is the exact-search baseline that 06.3 benchmarks and 06.5's NumPy store reproduces.
6.2 An eval-results table#
Per-prompt scores for two models, pivoted for comparison, with means and failure rows — the "which model is better" question in one script. The input file eval_results.csv (16 rows: 8 prompts × 2 models):
prompt_id,model,score,passed
p01,gpt-6-luna,0.91,1
p01,claude-haiku-5-5,0.88,1
p02,gpt-6-luna,0.76,1
p02,claude-haiku-5-5,0.54,0
p03,gpt-6-luna,0.83,1
p03,claude-haiku-5-5,0.79,1
p04,gpt-6-luna,0.62,0
p04,claude-haiku-5-5,0.71,1
p05,gpt-6-luna,0.95,1
p05,claude-haiku-5-5,0.92,1
p06,gpt-6-luna,0.58,0
p06,claude-haiku-5-5,0.66,1
p07,gpt-6-luna,0.87,1
p07,claude-haiku-5-5,0.90,1
p08,gpt-6-luna,0.44,0
p08,claude-haiku-5-5,0.51,0# eval_report.py — needs: uv add pandas
import pandas as pd
df = pd.read_csv("eval_results.csv") # prompt_id, model, score, passed
# Per-model summary: mean score, count, pass rate
summary = (df.groupby("model")["score"]
.agg(mean_score="mean", n="size")
.assign(pass_rate=lambda d: df.groupby("model")["passed"].mean()
.reindex(d.index)))
print(summary.round(3))
# Wide view: one row per prompt, one column per model — the comparison table
pivot = df.pivot_table(index="prompt_id", columns="model",
values="score", aggfunc="mean")
delta = pivot["gpt-6-luna"] - pivot["claude-haiku-5-5"]
# Rank prompts by |delta|, then show the signed gap for the top 3
gap_rank = delta.abs().sort_values(ascending=False)
print("\nLargest gaps (gpt-6-luna minus claude-haiku-5-5):")
print(delta.loc[gap_rank.head(3).index])
# The rows worth a human look: anything either model failed
fails = df[df["passed"] == False]
print(f"\n{len(fails)} failed runs:")
print(fails[["prompt_id", "model", "score"]].to_string(index=False)) mean_score n pass_rate
model
claude-haiku-5-5 0.739 8 0.750
gpt-6-luna 0.745 8 0.625
Largest gaps (gpt-6-luna minus claude-haiku-5-5):
prompt_id
p02 0.22
p04 -0.09
p06 -0.08
dtype: float64
5 failed runs:
prompt_id model score
p02 claude-haiku-5-5 0.54
p04 gpt-6-luna 0.62
p06 gpt-6-luna 0.58
p08 gpt-6-luna 0.44
p08 claude-haiku-5-5 0.51The shape of the answer — "gpt-6-luna edges on mean score (0.745 vs 0.739) and takes the biggest single gap (p02, +0.22), but passes fewer prompts overall (5/8 vs 6/8)" — is what eval analysis in Module 10A looks like at the table level. 10A.2 §1.4 covers the dataset formats this CSV came from.
6.3 A usage-and-cost log#
Tokens per call × price per model = cost; group by day and by model. This is the table 03.7 teaches you to emit and 11A.2 teaches you to monitor — pandas is how you analyse the export. The input file usage_log.csv (6 rows across 3 days):
date,model,input_tokens,output_tokens
2026-10-28,gpt-6-luna,12400,3100
2026-10-28,claude-haiku-5-5,9800,2600
2026-10-29,gpt-6-luna,15200,4200
2026-10-29,claude-haiku-5-5,11000,3400
2026-10-30,gpt-6-luna,9800,2800
2026-10-30,claude-haiku-5-5,13400,3900# cost_report.py — needs: uv add pandas
import pandas as pd
# Illustrative prices per 1M tokens — replace with your provider's current
# pricing (03.7 Part 3 shows how to compute exact cost per call).
PRICE = {"gpt-6-luna": (0.10, 0.40), "claude-haiku-5-5": (0.08, 0.32)}
df = pd.read_csv("usage_log.csv") # date, model, input_tokens, output_tokens
df["cost_usd"] = [
(r.input_tokens * PRICE[r.model][0] + r.output_tokens * PRICE[r.model][1]) / 1e6
for r in df.itertuples()
]
print("== cost by model ==")
print(df.groupby("model")["cost_usd"].agg(["sum", "count"]).round(4))
print("\n== cost by day ==")
print(df.groupby("date")["cost_usd"].sum().round(4))
print("\n== tokens per dollar (efficiency) ==")
eff = df.groupby("model").apply(
lambda g: g[["input_tokens", "output_tokens"]].sum().sum() / g["cost_usd"].sum(),
include_groups=False)
print(eff.round(0).astype("int64"))== cost by model ==
sum count
model
claude-haiku-5-5 0.0059 3
gpt-6-luna 0.0078 3
== cost by day ==
date
2026-10-28 0.0041
2026-10-29 0.0052
2026-10-30 0.0044
Name: cost_usd, dtype: float64
== tokens per dollar (efficiency) ==
model
claude-haiku-5-5 7469512
gpt-6-luna 6105398
dtype: int64The itertuples row loop is fine at thousands of rows; at millions you'd vectorize the price lookup with df["model"].map(dict) instead — 5.11 is the rule. The point stands: once the log is a DataFrame, "cost by day", "tokens per dollar" and "which model is cheapest per task" are one-liners.
6.4 Cleaning a messy tickets CSV#
The CSV an export actually gives you: mixed case, whitespace, N/A, missing priorities, dates in two formats. Here is tickets_raw.csv exactly as it arrives — note the quoted subject with stray spaces, the empty cells, the N/A, and the MM/DD/YYYY dates mixed in with ISO ones:
ticket_id,subject,priority,opened,agent
T-1001," reset password email ",HIGH,2026-10-28,alice
T-1002,Invoice Total Mismatch,,10/29/2026,bob
T-1003,api rate limit help,N/A,2026-10-30,carol
T-1004,,,2026-10-31,dave
T-1005,export stuck at 90%,URGENT,not-a-date,erin
T-1006,duplicate charge refund, Medium ,11/01/2026,alice# clean_tickets.py — needs: uv add pandas
import pandas as pd
df = pd.read_csv("tickets_raw.csv")
print(f"raw: {df.shape}, missing per column:\n{df.isna().sum()}")
# Normalize the easy wins first. Note: read_csv already turned the literal "N/A"
# in T-1003 into NaN — it is one of pandas' default na_values (see the note below).
df["priority"] = df["priority"].str.strip().str.lower()
df["priority"] = df["priority"].fillna("medium") # domain default; counted above
df["subject"] = df["subject"].str.strip().str.title()
df["opened"] = pd.to_datetime(df["opened"], errors="coerce", format="mixed")
# Count what coercion destroyed — never clean silently
dropped = df["opened"].isna().sum()
print(f"coerced {dropped} unparseable dates to NaT")
# The clean frame, ready for the next pipeline stage
df = df.dropna(subset=["ticket_id", "subject"]).reset_index(drop=True)
df.to_csv("tickets_clean.csv", index=False)
print(df.head(3).to_string(index=False))raw: (6, 5), missing per column:
ticket_id 0
subject 1
priority 3
opened 0
agent 0
dtype: int64
coerced 1 unparseable dates to NaT
ticket_id subject priority opened agent
T-1001 Reset Password Email high 2026-10-28 alice
T-1002 Invoice Total Mismatch medium 2026-10-29 bob
T-1003 Api Rate Limit Help medium 2026-10-30 carolLook at the priority count: three missing, although only two cells are empty. read_csv silently converted the literal text N/A into NaN as well, because N/A is on pandas' default list of missing-value strings ("", "NA", "N/A", "n/a", "NULL", "None", "nan" and a few more — see the na_values entry in the read_csv docs). That is usually what you want, and sometimes a trap: a real value that happens to spell NA (a country code for Namibia, a person called Null) is lost on read. When a column can contain such values, pass keep_default_na=False and list the sentinels you mean in na_values=[...].
The discipline shown — strip, case-fold, coerce with errors="coerce", count the casualties, drop only on keys — is the pandas-level version of 05.5's cleaning contract and 05.10's stage checks. pandas is the tool; the decisions are the skill.
Part 7: What the standard library does underneath#
Deep-dive
Before the libraries existed, all of this was hand-rolled for loops over lists. Running the same computations in pure Python is the best way to understand what NumPy and pandas actually accelerate — and to verify results without trusting a black box.
7.1 Pure-Python cosine similarity and ranking#
# stdlib_cosine.py — no imports beyond math; run it: python3 stdlib_cosine.py
import math
docs = {
"d1 budget-laptop-deals": [0.90, 0.10, 0.80, 0.20],
"d2 enterprise-server-pricing": [0.70, 0.90, 0.10, 0.80],
"d3 student-discount-guide": [0.80, 0.30, 0.60, 0.40],
"d4 luxury-watch-review": [0.20, 0.70, 0.50, 0.90],
"d5 warranty-returns-policy": [0.50, 0.20, 0.40, 0.70],
}
query = [0.85, 0.15, 0.70, 0.30] # "cheap laptop for students"
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def norm(v):
return math.sqrt(dot(v, v))
def cosine(a, b):
return dot(a, b) / (norm(a) * norm(b))
scores = sorted(
((name, cosine(query, vec)) for name, vec in docs.items()),
key=lambda item: item[1],
reverse=True,
)
for name, score in scores:
print(f"{score:.4f} {name}")0.9931 d1 budget-laptop-deals
0.9829 d3 student-discount-guide
0.8468 d5 warranty-returns-policy
0.6470 d2 enterprise-server-pricing
0.6166 d4 luxury-watch-reviewIdentical ranking to the NumPy version in 6.1 — which is exactly the point: docs_n @ q_n is this same arithmetic, done in C over contiguous memory. The Python version allocates a generator, calls zip, sum, math.sqrt per element; the NumPy version makes one call. For 5 docs nobody cares; for 40,000 docs × 768 dims the Python version is the difference between a coffee break and a coffee.
7.2 csv + collections aggregation#
The same two analyses from Part 6, in the standard library:
# stdlib_aggregate.py — run it: python3 stdlib_aggregate.py
import csv
import statistics
from collections import defaultdict
by_model = defaultdict(list)
passes = defaultdict(int)
with open("eval_results.csv", newline="") as f:
for row in csv.DictReader(f):
by_model[row["model"]].append(float(row["score"]))
passes[row["model"]] += int(row["passed"])
print("== eval: mean score / pass count per model ==")
for model, scores in sorted(by_model.items()):
n = len(scores)
print(f"{model:22s} mean={statistics.fmean(scores):.3f} "
f"n={n} passed={passes[model]}/{n}")
PRICE = {"gpt-6-luna": (0.10, 0.40), "claude-haiku-5-5": (0.08, 0.32)}
daily = defaultdict(float)
with open("usage_log.csv", newline="") as f:
for row in csv.DictReader(f):
pin, pout = PRICE[row["model"]]
cost = (int(row["input_tokens"]) * pin
+ int(row["output_tokens"]) * pout) / 1_000_000
daily[row["date"]] += cost
print("== usage: total USD per day ==")
for day in sorted(daily):
print(f"{day} ${daily[day]:.4f}")== eval: mean score / pass count per model ==
claude-haiku-5-5 mean=0.739 n=8 passed=6/8
gpt-6-luna mean=0.745 n=8 passed=5/8
== usage: total USD per day ==
2026-10-28 $0.0041
2026-10-29 $0.0052
2026-10-30 $0.0044defaultdict(list) is groupby for the simple cases; statistics.fmean is .mean(); csv.DictReader is read_csv minus the dtype inference, the missing-value handling, the joins and the pivots. The stdlib version is ~30 lines for what pandas does in 3 — and it breaks the moment you want a pivot table, a groupby with two keys, or a merge. That gap is the product pandas sells.
7.3 Why the libraries still win#
| What you hand-roll in stdlib | What the library gives you |
|---|---|
Nested loops + zip for dot products |
Contiguous memory + compiled loops (10–100× on large arrays, typically) |
defaultdict + manual aggregation |
groupby().agg() with named outputs, multiple functions, categorical keys |
csv + DictReader + manual dtype parsing |
read_csv with inference, dtype=, parse_dates, usecols, chunksize |
| Dict-of-lists for "columns" | Labelled alignment: operations line up on the index automatically |
| Sorting whole lists for top-k | argpartition partial selection |
The honest summary: for five rows, the stdlib is fine and dependency-free. For the sizes AI data actually reaches — thousands of embeddings, millions of log lines — the libraries aren't a convenience, they're the difference between feasible and not.
Part 8: When NOT to reach for these — and how to work with them#
Deep-dive
8.1 The decision table: list vs array vs table vs SQL#
| Your data looks like... | Reach for | Because |
|---|---|---|
| A handful of numbers, heterogeneous types, quick script | Python list/dict |
No dependency, perfectly readable at small sizes |
| Many same-typed numbers you will do maths on (embeddings, scores, features) | NumPy ndarray |
Contiguous memory, vectorized ops, the API the AI ecosystem speaks |
| Rows with names: logs, eval results, CSVs, experiment tables | pandas DataFrame |
Labels, dtypes, missing data, groupby/merge/pivot built in |
| Data already in a database, or bigger than RAM | SQL (SQLite/Postgres) — filter and aggregate server-side, read_sql for the result |
Databases are built for exactly this; don't pull a million rows to count them in pandas |
| Files too big for pandas but not worth a server | DuckDB | SQL engine over CSV/Parquet files, columnar and fast — the "pandas-shaped SQL" answer |
| DataFrames at a scale/polish pandas can't reach | Polars | Lazy evaluation, multi-threading, stricter dtypes — the modern alternative, steeper learning curve |
| Embedding matrices at search scale | Vector DB / FAISS (06.4, 06.5) | ANN indexes; NumPy brute force is the baseline they beat |
The rule of thumb that resolves most arguments: push computation to where the data lives. Filter and aggregate in SQL when the data is in SQL; convert to pandas when you need labelled reshaping it can't express; convert to NumPy when you need raw numeric speed.
8.2 Scale thresholds, honestly#
There are no magic numbers, but these orders of magnitude are useful:
- NumPy dot products / matmul: trivial to ~1M elements, comfortable to ~100M, memory-bound beyond. A
(40k, 768) @ (768,)is milliseconds;(1M, 768) @ (768, 768)is a real matrix multiply — seconds, and you should ask whether you need it. - pandas in memory: comfortable to a few million rows × tens of columns; painful beyond ~1 GB of data. Past that,
chunksize,usecols,categorydtypes, DuckDB or SQL. - Cosine search brute force: exact k-NN over
ndocs costsO(n·d)per query — fine to ~100k docs, the point where ANN indexes start paying for themselves (06.3 works the arithmetic).
8.3 Workflow tips: notebooks, plotting and reading docs#
- Notebooks are for exploration, scripts are for results. Jupyter/marimo/VS Code notebooks are excellent for eyeballing an embedding matrix or a DataFrame head; they are terrible for reproducible pipelines (hidden state, out-of-order execution, no version control). The pattern that works: explore in a notebook, then move the working code into a
scripts/file in the uv project and run it withuv run python. 01B.1 covers the notebook-kernel setup. - Plotting is one import away, not a lesson.
matplotlib/seaborn/plotlyproduce the charts; this lesson doesn't teach them. If you need a quick visual sanity check of embeddings,matplotlib's scatter of a PCA projection is the standard trick — 02.3 §9 does it in NumPy. - Reading these docs: both libraries have extensive official user guides — the NumPy user guide and the pandas user guide. For "how do I do X", the pandas user guide's cookbook-style sections and NumPy's "absolute basics for beginners" are the right first stops. When versions disagree (pandas 2 vs 3 especially), check the whatsnew notes — several "bugs" are intended behaviour changes.
The failure gallery#
The mistakes below are the ones that actually reach production. Each shows the symptom, the cause, and the fix.
| Symptom | Cause | Fix |
|---|---|---|
ValueError: operands could not be broadcast together with shapes (1000,768) (1000,) |
Trying to subtract a per-row vector (n,) from an (n, d) matrix — it aligned with the last axis |
Make it a column: matrix - vectors[:, None] |
Filtered assignment does nothing to df (pandas 3) |
df[df["score"] > 0.8]["passed"] = True — chained assignment on a copy; pandas 3 (checked against 3.1) flags it with a ChainedAssignmentError warning, but the data is not changed |
mask = df["score"] > 0.8; df.loc[mask, "passed"] = True |
merge raises ValueError: You are trying to merge on ... and int64 columns, or a left join returns NaN in every right-hand column |
Key dtypes differ ("42" vs 42), or the text keys differ in format ("042" vs "42", trailing spaces, case) |
Normalize both sides before merge: df["id"] = df["id"].astype("int64") or .str.strip().str.lower(); check merged["col"].isna().sum() afterwards |
SettingWithCopyWarning in old code / ChainedAssignmentError warning in pandas 3 |
Mutating a slice of a slice | Work on .loc masks or explicit .copy() snapshots |
Every cosine score is NaN |
One NaN in the embedding matrix poisons every dot product touching it |
np.isnan(m).any(axis=1) → find and drop/fix the row before the matmul |
read_json reads the whole JSONL file as one record and errors |
Missing lines=True — it expects a single JSON document |
pd.read_json(path, lines=True) |
| Ticket IDs lose leading zeros / become floats | read_csv type inference guessed wrong |
pd.read_csv(path, dtype={"ticket_id": "string"}) |
df.loc[0] returns the wrong row after sorting |
.loc is label-based; the label moved with the row |
Use .iloc for position, or df = df.reset_index(drop=True) first |
ValueError: assignment destination is read-only on a slice |
Parent array is read-only (e.g. np.load(..., mmap_mode="r")) |
arr = arr.copy() if you need to write, or load without mmap_mode |
Integer column with one blank becomes 1.0, 2.0… |
pandas upcast int64 → float64 because int64 can't hold missing |
Use nullable Int64 dtype |
Two tracebacks worth recognizing on sight:
ValueError: operands could not be broadcast together with shapes (1000,768) (1000,)That's a (1000,) vector of per-row values trying to combine with a (1000, 768) matrix — it aligned with the last axis (768) and failed. You forgot [:, None] to make it a (1000, 1) column. (A plain (768,) query vector broadcasts fine against (1000, 768) — that pairing can never raise this error.)
Traceback (most recent call last):
...
File "report.py", line 12, in <module>
pivot["gpt-6-luna"] - pivot["claude-haiku-5-5"]
KeyError: 'gpt-6-luna'pivot_table names columns after the values it found — if your model column had different strings (a typo, a trailing space, "GPT-6-Luna"), the expected column simply doesn't exist. Check pivot.columns.tolist() before indexing; normalize the key column first (.str.strip().str.lower()).
Common misconceptions#
| Misconception | Reality |
|---|---|
| "You need NumPy/pandas to call an LLM API." | You don't — the SDKs speak JSON. These libraries handle the data around the call: embeddings, evals, logs, CSVs. |
| "A Python list of floats is basically a NumPy array." | A list stores pointers to boxed float objects; an array stores contiguous typed bytes. Memory and speed differ by orders of magnitude at embedding scale. |
"arr[1:3] = 0 copies the slice first." |
Basic slicing is a view — it shares memory, so the assignment writes through to the original. Use .copy() when you need independence. |
| "Cosine similarity and dot product are the same thing." | Only for unit-normalized vectors. Otherwise cosine divides by the lengths; raw dot product conflates direction with magnitude. |
"df.loc[0] always means the first row." |
.loc is label-based: after sorting or filtering, label 0 may not be first — or may not exist. .iloc[0] is positional. |
"df["col"] = value inside a filter modifies the original." |
In pandas 3 it doesn't — chained assignment never updates the original now (SettingWithCopyWarning is gone; a ChainedAssignmentError warning points at the line). Use .loc[mask, "col"] = value. |
"pandas string columns are object dtype." |
In pandas 3 they get a dedicated str dtype (PyArrow-backed when installed). dtype == object checks break. |
"Missing values are all NaN." |
pandas uses NaN (float), NaT (datetime), NA (nullable dtypes) and None (object columns). isna() covers them all — never test with == None. |
"fillna(0) is a safe default for missing scores." |
It invents data: a missing eval score is not a zero. Decide per column whether to drop, fill with a domain value, or flag — and count what you changed. |
| "pandas can handle any size data if you're patient." | It's single-machine, in-memory. Multi-GB data needs chunksize, DuckDB/SQL, or Polars — not a bigger workstation. |
| "NumPy is only for scientists." | It's the substrate of the AI ecosystem: embeddings, eval scores, token counts — if it's a grid of numbers, NumPy is how Python does maths on it fast. |
| "I should learn all of pandas before using it." | The 20% in this lesson covers most AI-engineering work; the user guide has the rest when you need it. |
Key takeaways#
- NumPy arrays are contiguous, typed grids of numbers: fast because the per-element work happens in compiled code, not the Python interpreter.
float32is the embedding dtype;float64is the safe default. - Broadcasting aligns shapes from the right and stretches size-1 dims — the mechanism behind "add this vector to every row". When it fails, it's almost always an
axis/[:, None]mistake. axis=collapses that axis:axis=0summarizes per column,axis=1per row on a(rows, cols)array. Check it before trusting a "transposed-looking" result.- Views vs copies: basic slicing shares memory (writes go through); fancy indexing and
concatenate/stackcopy..copy()when you need independence. - The retrieval pattern: normalize embeddings once, then
scores = docs @ queryis one matmul;argpartitionpicks top-k without a full sort. This is the exact-search baseline every vector store implements or approximates. - Cosine similarity = angle between vectors, length-independent; for unit vectors it's just the dot product.
np.isclose, never==, on floats; watch forNaNpoisoning. - pandas DataFrames are labelled tables:
Series+ named columns + index..locis label-based,.ilocpositional; boolean masks are the workhorse;groupby/merge/pivot_table/meltcover the reshaping jobs. - Missing data is a decision, not a default:
isna()/fillna/dropna/to_numeric(coerce)— and always count what coercion or dropping removed. - pandas 3 changed the contract: Copy-on-Write means chained assignment never updates the original (and warns) and
inplace=is deprecated; string columns get astrdtype; large CSVs read in parallel by default. - Know the ceiling: pandas is for labelled in-memory data; SQL/DuckDB for bigger-than-RAM or already-in-a-database; Polars as the modern alternative; vector DBs for embedding search at scale.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| ndarray | NumPy's N-dimensional array: a grid of same-typed numbers in contiguous memory |
| dtype | The element type of an array or column (float32, int64, str, bool...) |
| shape / ndim / axis | An array's dimension sizes / its number of dimensions / one of those dimensions, numbered from 0 |
| view vs copy | A slice sharing the parent's memory vs an independent duplicate |
| fancy indexing | Indexing with a list/array of integers or booleans — always copies |
| broadcasting | Aligning array shapes from the right and stretching size-1 dims so operations apply element-wise |
| reduction | An operation collapsing an axis (sum, mean, max, argmax...) |
| argpartition | Partial selection: top-k positions without sorting everything |
| unit vector | A vector divided by its norm — length 1, direction preserved |
| cosine similarity | (a·b)/(‖a‖·‖b‖): angle-based similarity in [-1, 1]; equals dot product for unit vectors |
| Series | pandas' one-column labelled array |
| DataFrame | pandas' labelled table of named columns sharing an index |
| index | The row labels of a pandas object; what .loc selects on |
.loc / .iloc |
Label-based / position-based selection |
| boolean mask | A True/False Series or array used to filter rows |
json_normalize |
pandas function that flattens nested JSON records (e.g. a usage object) into dotted columns |
groupby |
Split-apply-combine: aggregate or transform per key |
merge / concat |
Labelled join on keys / stacking tables row-wise or column-wise |
pivot_table / melt |
Long-to-wide grouped reshape / wide-to-long unpivot |
sort_values / sort_index |
Ordering rows by a column's values / by the index labels |
method chaining / .pipe() |
Composing pandas operations into one fluent expression; pipe injects a whole-frame function step |
.str / .dt accessors |
Vectorized string / datetime methods on a column |
isna / fillna / dropna |
Detect / replace / remove missing values |
| nullable dtypes | Int64, boolean, string dtypes that represent missing properly |
| Copy-on-Write (CoW) | pandas 3 semantics: every derived object behaves as a copy; chained assignment does nothing |
str dtype |
pandas 3's dedicated string dtype (PyArrow-backed when installed), replacing object for text |
read_sql |
pandas' bridge to SQL databases via DBAPI connections |
| JSONL | One JSON object per line — the log/eval-set interchange format |
| Parquet | Columnar, typed, compressed table format; needs pyarrow in pandas |
memory-mapping (mmap_mode) |
Loading a .npy lazily from disk instead of into RAM |
All terms are also collected in the glossary.
Where you'll use this in the AI path#
- 02.3 — Embeddings: cosine similarity, dot products and the "meaning as geometry" idea this lesson's Part 4 computes.
- 06.1 — Embedding Models and APIs: whether provider vectors arrive normalized — the fact that decides if you can skip norms at query time.
- 06.2 — Embedding Pipelines: batch embedding at scale, where
np.stackturns per-document vectors into the matrix. - 06.3 — Similarity and Distance:
argpartitiontop-k andfloat32/float16precision, benchmarked. - 06.5 — Vector Databases: the pure-NumPy brute-force store this lesson's pattern reproduces.
- 10A.2 — Building Evaluation Datasets: JSONL/Parquet dataset formats your eval tables come in.
- 11A.2 — Metrics, SLOs and Alerting: cost monitoring — the usage-log analysis of 6.3 at production scale.
- 05.5 — Cleaning and Normalization: the cleaning discipline behind 6.4.
Exercises#
- Broadcasting (3.1):
a = np.ones((3, 4)),b = np.arange(4). What isa + b's shape and what does each row contain? Now trya + np.arange(3)— what error do you get and why? - Views (2.5):
m = np.arange(6).reshape(2, 3); sub = m[:, 0]; sub[0] = 99. What ismnow? How would you makesubindependent? - dtype (2.3):
np.array([0.1, 0.2]).dtypegives what? Andnp.array([0.1, 0.2], dtype=np.float32).dtype? Why do embeddings prefer the second? - Cosine by hand (4.3): compute
cosine([1, 0], [1, 1])mentally — what do you get, and why does that match the "angle" interpretation? - Top-k (3.3/4.4): for
scores = np.array([0.2, 0.9, 0.5, 0.7, 0.1]), write the two lines that return the indices of the top-2 scores in descending order usingargpartition. - pandas selection (5.4): given the eval
df, write the one-liner that returns only rows wherescore < 0.7andmodelcontains"luna". - Missing data (5.5): a CSV
scorecolumn holds0.9, an empty cell,0.4and the textpending. What dtype doesread_csvinfer, and what doespd.to_numeric(..., errors="coerce")produce? How many values are missing afterwards? (Then: what would the dtype have been if the last cell saidN/Ainstead ofpending?) - groupby (5.8): write the
groupbyexpression that yields, per model, both the meanscoreand the count of rows — in oneaggcall with named outputs. - pivot (5.10): using the eval table, produce a DataFrame with
prompt_idas rows andmodelas columns showingscore. Which function? - Chained assignment (5.14): explain why
df[df["score"] > 0.8]["passed"] = Truedoes not changedfin pandas 3, and write the correct two-line version. - stdlib vs library (7): in the stdlib cosine script, what would change if
docshad 40,000 entries instead of 5? Which line of the NumPy version is doing the equivalent work? - NaN poisoning (4.5): if one row of
docscontains aNaN, what happens todocs_n @ q_n? How would you detect it before the matmul? - Sorting and chaining (5.16): using the eval
df, write one chained expression returning the five highest-scorerows forgpt-6-lunawith a freshRangeIndex. Whichsort_valuesoption would put missing scores first instead of last?
Solutions
a + bis(3, 4):bis treated as a row(1, 4)stretched to(3, 4), so every row of the result is1 + [0,1,2,3]=[1,2,3,4].a + np.arange(3)fails:(3,)aligns with the last axis of size 4 →ValueError: operands could not be broadcast together. Fix:a + np.arange(3)[:, None]to make it a(3,1)column.mbecomes[[99, 1, 2], [3, 4, 5]]— the slice shares memory.sub = m[:, 0].copy()(ornp.array(m[:, 0])) makes it independent.float64(Python floats default to double) vsfloat32. Embeddings preferfloat32: half the memory offloat64, matches what embedding APIs return, and the precision is already approximate —float64buys nothing.cosine = (1*1 + 0*1) / (1 * sqrt(2)) = 1/√2 ≈ 0.707. The vectors are 45° apart — neither identical (1.0) nor orthogonal (0.0), matching the geometric picture.idx = np.argpartition(-scores, 1)[:2]gives the two largest positions unordered;idx[np.argsort(-scores[idx])]orders them best-first →[1, 3](scores 0.9 and 0.7) — the same idiom as 4.4.df[(df["score"] < 0.7) & (df["model"].str.contains("luna"))]— note the&(notand) and parentheses around each mask.- pandas infers the text dtype (
strin pandas 3,objectearlier):pendingis not one of the default missing-value strings, so the whole column stays text, with a realNaNonly for the empty cell.pd.to_numeric(..., errors="coerce")gives[0.9, NaN, 0.4, NaN]asfloat64— 2 values are missing (1 was already missing, 1 was created by the coercion). WithN/Ainstead ofpending,read_csvwould have converted it toNaNon read, so the column would already befloat64with 2 missing values and nothing left to coerce (6.4 explains the defaultna_valueslist). df.groupby("model")["score"].agg(mean_score="mean", n="size")— named aggregation produces columnsmean_scoreandn.df.pivot_table(index="prompt_id", columns="model", values="score", aggfunc="mean")(orpivotif no duplicates).- The filter returns a new DataFrame; assigning
["passed"] = Trueon it modifies the copy, notdf— and pandas 3 never writes it back todf(it flags the line with aChainedAssignmentErrorwarning). Correct:mask = df["score"] > 0.8thendf.loc[mask, "passed"] = True. - The Python version would do 40,000 × 768 ≈ 30M Python-level multiply-adds — minutes, not milliseconds. In the NumPy version,
docs_n @ q_nis that whole loop in one C call. - Every score touching that row becomes
NaN(dot product with NaN is NaN), andargsort/argpartitionput NaNs last, so with-scoresthose documents silently never appear in the top-k. Detect first:np.isnan(docs).any(axis=1)ornp.isfinite(docs).all(axis=1)and drop/fix offending rows before the matmul. df[df["model"] == "gpt-6-luna"].sort_values("score", ascending=False).head(5).reset_index(drop=True)— each step returns a new frame, so they compose.na_position="first"puts missing values at the top instead of the default last.
Check yourself#
- Why is a NumPy array faster than a Python list of floats for the same numbers?Contiguous typed memory (no per-element object pointers) and compiled C loops instead of per-element Python bytecode — typically one to two orders of magnitude faster at scale.
- What does
dtype=float32cost you versusfloat64, and why is it still the right choice for embeddings?~7 significant decimal digits and half the memory offloat64. Embeddings are already approximations from lossy training/quantization, so the extra precision buys nothing while doubling memory and bandwidth. - What is broadcasting, in one sentence?Dimensions align from the right and size-1 (or missing) dims stretch to match, so operations apply element-wise across compatible shapes.
- On a
(docs, dims)matrix, what doesaxis=0vsaxis=1mean forsum()?axis=0collapses rows → one value per column (per embedding dimension);axis=1collapses columns → one value per row (per document). - Why does
m[:, 0][0] = 99changem, and when would you not want that?Basic slicing is a view sharing memory, so the write goes through tom. You'd want independence (.copy()) when the subset must not mutate the source. - What is the difference between
.locand.iloc?.locselects by index label;.ilocselects by integer position regardless of labels. - Write the cosine-similarity formula and explain why normalized vectors make it a dot product.
cos(a,b) = (a·b)/(‖a‖·‖b‖). For unit vectors ‖a‖=‖b‖=1, so it reduces toa·b. - What does
argpartitionbuy you overargsortfor top-k?It selects the top-k without sorting all n elements — O(n) selection vs O(n log n) sort. - Name three ways pandas represents "missing" and the one function that detects all of them.
NaN(float),NaT(datetime),NA/None(nullable/object).isna()(orpd.isna) detects all of them. - What are the two big pandas 3 changes that break pandas-2-era code?Copy-on-Write semantics (chained assignment never updates the original;
inplace=deprecated) and the dedicatedstrdtype replacingobjectfor text. df["score"] > 0.8produces what kind of object, and how do you use it to filter rows?A booleanSeriesmask;df[df["score"] > 0.8]ordf.loc[df["score"] > 0.8]filters rows.- When should you reach for SQL or DuckDB instead of pandas?When data is already in a database, bigger than RAM, or needs server-side aggregation — push compute to where the data lives.
- What does
read_json(..., lines=True)parse, and why islines=Trueneeded?JSONL — one JSON object per line;lines=Truetells pandas each line is a separate record rather than one JSON document. - Why is
df["col"].str.contains(".")dangerous, and how do you fix it?.is a regex metacharacter matching any char; passregex=Falsefor literal substring search or escape the pattern. - What is the difference between
df.sort_values("score")anddf.sort_index()?sort_valuesorders rows by a column's values;sort_indexorders by the index labels — which after filtering or sorting are no longer positional.
Further resources#
- NumPy documentation — the user guide (basics, broadcasting, indexing) and the API reference for every function used here.
- NumPy 2.0 migration guide and the 2.x release notes — for the promotion, dtype and removed-alias changes.
- pandas documentation — the user guide (indexing, groupby, reshaping, missing data, IO) and the 10-minute introduction.
- pandas 3.0.0 and 3.1.0 release notes — the Copy-on-Write,
strdtype andread_csvchanges. - pandas Cookbook — task-shaped recipes for the operations this lesson only sketches.
- NumPy: the absolute basics for beginners — the gentlest official path if Part 2 moved too fast.
← 01B.10 — Logging, Debugging and Packaging: Putting the Toolkit Together | Module 01B overview | Module 01C: Concurrency, Parallelism and Python Internals →