NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
What you will learn
- Read an array's shape and pick the right axis
- Normalise 1,000 embeddings with broadcasting and score them with one @
- Load a call log with the right types, then count missing values and filter
- Summarise the log with groupby, merge, resample and hand a column back to NumPy
Before you start
- Basic Python
Every embedding, every score and every log you meet as an AI engineer is either an array or a table. So here's NumPy and pandas in one pass, at the depth you actually need and not more.
We'll use NumPy 2.5.4 and pandas 3.1.1 on two generated sample files: 1,000 embedding vectors of 384 numbers each, and a one-week log of 2,000 model calls from a help-desk assistant. Nothing here needs an API key.
An egg carton and a spreadsheet
Think of an egg carton: one kind of thing, in a fixed grid, two by six. That's a NumPy array: only numbers, one data type, and a shape.
Now think of a spreadsheet. Each column has a name, and each column can hold a different kind of thing: times, words, numbers. That's a pandas DataFrame: rows and named columns.
Embeddings and scores are arrays. Logs and results are tables.
A list is not a vector
First, a surprise that catches a lot of people. Multiply a plain Python list by 2, then the same numbers as a NumPy array:
import numpy as np
scores = [0.2, 0.5, 0.9]
print("[0.2, 0.5, 0.9] * 2 =", scores * 2)
scores = np.array([0.2, 0.5, 0.9])
print("np.array([0.2, 0.5, 0.9]) * 2 =", scores * 2)
[0.2, 0.5, 0.9] * 2 = [0.2, 0.5, 0.9, 0.2, 0.5, 0.9]
np.array([0.2, 0.5, 0.9]) * 2 = [0.4 1. 1.8]
The list didn't double the numbers. It repeated itself, so we got six items. The array multiplied every number. Same symbol, different meaning: when you want maths on numbers, you want an array.
Shape, and the axis you collapse
The most important word in NumPy is shape. Our embeddings file loads as one array:
from pathlib import Path
DATA = Path(__file__).resolve().parent / "data"
vectors = np.load(DATA / "embeddings.npy")
print("embeddings.shape =", vectors.shape, " dtype =", vectors.dtype)
print("first vector, first 4 numbers:", np.round(vectors[0, :4], 3))
print("mean over axis=0 (per column) ->", vectors.mean(axis=0).shape)
print("mean over axis=1 (per row) ->", vectors.mean(axis=1).shape)
embeddings.shape = (1000, 384) dtype = float32
first vector, first 4 numbers: [-1.203 0.566 0.311 0.783]
mean over axis=0 (per column) -> (384,)
mean over axis=1 (per row) -> (1000,)
A thousand rows, one per text, and 384 numbers in each row. The axis is the direction you squash. The axis you name is the one that disappears.
Broadcasting: divide every row by its own length
Vector search compares directions, so first every row is scaled to length 1. np.linalg.norm(..., axis=1) gives each row's length, and keepdims=True keeps the result as a column:
lengths = np.linalg.norm(vectors, axis=1, keepdims=True)
print("lengths.shape =", lengths.shape)
unit = vectors / lengths
print("length of row 0 after:", round(float(np.linalg.norm(unit[0])), 4))
lengths.shape = (1000, 1)
length of row 0 after: 1.0
That's a (1000, 384) array divided by a (1000, 1) array. NumPy stretches the smaller one across each row, so every row is divided by its own length. This is broadcasting, and keepdims=True is what keeps that 1. Without it, lengths would have shape (1000,), and NumPy would line it up against the 384 columns instead of the rows, so the division fails.
(1000, 1) column of lengths is stretched across all 384 columns. No copy, no loop.Vector search in five lines
With shape, axis and broadcasting, the core of vector search fits in one function:
def top_k(vectors: np.ndarray, query: np.ndarray, k: int = 3) -> tuple[np.ndarray, np.ndarray]:
"""Rows most similar to the query: normalise every row, one matrix-vector product, sort."""
unit_rows = vectors / np.linalg.norm(vectors, axis=1, keepdims=True) # (1000, 384) / (1000, 1)
unit_query = query / np.linalg.norm(query)
scores = unit_rows @ unit_query # (1000,)
best = np.argsort(scores)[::-1][:k]
return best, scores[best]
query = vectors[42] + np.float32(0.1)
best, best_scores = top_k(vectors, query)
for row, score in zip(best, best_scores):
print(f"row {row:4d} score {score:.3f}")
row 42 score 0.995
row 688 score 0.143
row 380 score 0.139
The @ sign is one matrix-vector product: all 1,000 scores at once, shape (1000,). argsort sorts them smallest first, [::-1] reverses, and [:k] keeps the top 3. Row 42 wins at 0.995 and the next rows are far behind. That makes sense: the query was built from row 42. The search itself, with thresholds and scikit-learn's NearestNeighbors, is covered in Similarity Search: Finding the Closest Vectors.
Loop vs vectorised
Why not just write a loop? Here's the same dot product, both ways:
import time
start = time.perf_counter()
loop_scores = [sum(float(a) * float(b) for a, b in zip(row, query)) for row in vectors]
loop_ms = (time.perf_counter() - start) * 1000
start = time.perf_counter()
fast_scores = vectors @ query
fast_ms = (time.perf_counter() - start) * 1000
print(f"python loop : {loop_ms:8.1f} ms")
print(f"vectors @ q : {fast_ms:8.3f} ms same answer: {np.allclose(loop_scores, fast_scores, rtol=1e-4)}")
python loop : 25.1 ms
vectors @ q : 0.182 ms same answer: True
The loop multiplies one pair of numbers at a time, 384,000 times. The @ runs the same maths in compiled code. On the lecture machine the loop took about 25 ms and @ less than a fifth of a millisecond, with the same answer. Your timings will differ; the gap won't. With a million documents instead of a thousand, that gap is the difference between instant and slow.
pandas: fix the types on load
Now the table. The log has one row per model call: when, which user, which route, which model, the tokens, the latency, the status and optional feedback.
import pandas as pd
pd.set_option("display.width", 120)
naive = pd.read_csv(DATA / "llm_calls.csv")
print(naive.head(3).to_string(index=False))
print("rows, columns:", naive.shape)
timestamp user_id route model input_tokens output_tokens latency_ms status feedback
2026-11-02T08:22:41 12 refund large-model 2421 452 4281.0 ok NaN
2026-11-02T08:32:21 12 refund large-model 1966 0 NaN rate_limited NaN
2026-11-02T08:33:01 5 order_status small-model 986 49 447.0 ok up
rows, columns: (2000, 9)
2,000 rows, 9 columns. But look at the timestamp's type:
print("dtype of timestamp:", naive["timestamp"].dtype)
try:
naive["timestamp"].dt.hour
except AttributeError as error:
print("AttributeError:", error)
dtype of timestamp: str
AttributeError: Can only use .dt accessor with datetimelike values
The CSV stores dates as text, and pandas doesn't guess. Asking for the hour fails. This is a very common bug, and the fix is one argument:
calls = pd.read_csv(DATA / "llm_calls.csv", parse_dates=["timestamp"])
print("dtype of timestamp:", calls["timestamp"].dtype)
print("first hour seen:", calls["timestamp"].dt.hour.iloc[0])
dtype of timestamp: datetime64[us]
first hour seen: 8
Always check your types right after loading. For a fuller health check of a new dataset (size, types, missing values, spread, balance, duplicates), see First Look at a Dataset.
Missing values and filters
Real logs have gaps. isna().sum() counts the missing values per column, and value_counts() tells us why:
print(calls.isna().sum()[lambda s: s > 0].to_string())
print(calls["status"].value_counts().to_string())
latency_ms 373
feedback 1336
status
ok 1627
rate_limited 189
error 184
189 rate-limited plus 184 errors is 373 failed calls, and a failed call has no latency. That's exactly the 373 missing latencies. Feedback is empty whenever the user gave no thumbs up or down.
A new column is one line of maths on whole columns, and a filter is a condition inside square brackets. & joins two conditions, and each one needs its own brackets:
calls["total_tokens"] = calls["input_tokens"] + calls["output_tokens"]
big = calls[(calls["status"] == "ok") & (calls["total_tokens"] > 3000)]
print(f"ok calls over 3,000 tokens: {len(big)} of {len(calls)}")
ok calls over 3,000 tokens: 138 of 2000
Group by model
This is the question you'll ask your logs again and again: how does each model behave? Keep the calls that worked, group by model, and compute several things at once with named aggregations:
def model_summary(calls: pd.DataFrame) -> pd.DataFrame:
ok = calls[calls["status"] == "ok"]
return ok.groupby("model").agg(
calls=("model", "size"),
avg_total_tokens=("total_tokens", "mean"),
median_latency_ms=("latency_ms", "median"),
p95_latency_ms=("latency_ms", lambda s: s.quantile(0.95)),
).round(0)
print(model_summary(calls).to_string())
calls avg_total_tokens median_latency_ms p95_latency_ms
model
large-model 493 2529.0 3480.0 5553.0
small-model 1134 1596.0 1128.0 1802.0
p95 means 95 out of 100 calls were faster than this. The large model's median is about 3.5 seconds and its p95 about 5.5. The small model is much faster on both. A table like this is the start of every cost and latency review.
Merge, resample, and back to NumPy
merge joins two tables on a shared column. The users table adds a team to every call, then we sum the tokens per team:
users = pd.read_csv(DATA / "users.csv")
by_team = calls.merge(users, on="user_id", how="left")
print(by_team.groupby("team")["total_tokens"].sum().sort_values(ascending=False).to_string())
team
engineering 811642
sales 790208
hr 717608
finance 683503
support 675909
Engineering used the most. Because the timestamp is now a real date, resample("D") counts calls per day:
print(calls.set_index("timestamp").resample("D").size().to_string())
timestamp
2026-11-02 167
2026-11-03 294
2026-11-04 280
2026-11-05 301
2026-11-06 264
2026-11-07 299
2026-11-08 306
2026-11-09 89
Freq: D
And to_numpy() hands a column back as an array, ready for any maths:
latencies = calls["latency_ms"].dropna().to_numpy()
print("type:", type(latencies).__name__, " shape:", latencies.shape)
type: ndarray shape: (1627,)
1,627 latencies, one per call that worked.
Common mistakes
- Doing maths on a Python list.
*repeats it. Convert withnp.arrayfirst. - Picking the wrong axis. Ask which dimension should disappear: rows (axis=0) or columns (axis=1).
- Dropping
keepdims=Truewhen you divide rows by their lengths. - Looping over vectors when one
@does it in compiled code. - Not checking dtypes on load. A date read as text breaks
.dtandresample. - Using
andinstead of&in a pandas filter, or forgetting the brackets around each condition.
Quick recap
| Move | Code | Result here |
|---|---|---|
| Read the shape | vectors.shape | (1000, 384), float32 |
| Collapse an axis | mean(axis=0) / mean(axis=1) | (384,) / (1000,) |
| Broadcast | vectors / lengths, keepdims=True | every row length 1.0 |
| Score all rows | unit_rows @ unit_query | row 42 at 0.995 |
| Types on load | parse_dates=["timestamp"] | datetime64[us] |
| Missing and filter | isna().sum(), & | 373 missing latencies; 138 big ok calls |
| Group | groupby("model").agg(...) | large 3480 ms median, small 1128 ms |
| Join and by day | merge, resample("D") | engineering on top; calls per day |
Try it yourself
- Change
kto 5 intop_kand run it again. - Group the log by
routeinstead of bymodel. - Remove
parse_datesand see which line fails first.
The project files and both data files are in the StudyEasy AI Community, free to join.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)