Python for AI Engineers · Part B · Lesson 16 of 26

pandas for AI engineers: clean data and build LLM eval reports

pandas for Java and JavaScript developers: Series and DataFrames, reading CSV and JSONL, loc and iloc, filters, missing data, cleaning text with .str, groupby, merge, pivot tables, and why vectorised code beats apply. You finish by building an eval report from LLM results.

⏱ 45 min3 exercises that check your codeRuns in your browser

By the end you can

  • Load CSV and JSONL results into a DataFrame and pick the rows and columns you need with [], loc, iloc and boolean filters
  • Add columns, handle missing data, and clean model answers with the .str methods
  • Summarise results with groupby, sort_values, merge and pivot_table, using vectorised code instead of apply
  • Build an eval report from LLM results (accuracy per category, latency and cost per model, worst cases) and export it to CSV and Markdown
1 / 6

1Series and DataFrame: a table in memory

pandas is the standard Python library for tables. Anything you would put in a spreadsheet or a SQL result (eval runs, chat logs, token usage, a list of documents to embed) fits in it. Install it in a project with uv add pandas; on this page it is already available. Everyone imports it as pd.

A DataFrame is a table: named columns, and rows with a label each (the index, by default 0, 1, 2 and so on). Each column is a Series: a one-dimensional array of values with that same index. Each column has one type for all its values (int64, float64, bool, text), which is what makes column maths fast.

The easiest way to build one is from a list of dicts, one dict per row: the shape you already get from JSON. print(df.to_string()) prints the whole table. Plain print(df) also works but hides rows and columns when the table is big or wide.

Try it: edit and run
import pandas as pd

pd.set_option("display.width", 120)      # how wide printed tables may be, in characters

rows = [
    {"model": "llama3.2:3b", "question": "Capital of France?", "latency_ms": 420, "correct": True},
    {"model": "llama3.2:3b", "question": "What is 2 + 2?", "latency_ms": 380, "correct": True},
    {"model": "qwen2.5:7b", "question": "Capital of France?", "latency_ms": 910, "correct": True},
    {"model": "qwen2.5:7b", "question": "What is 2 + 2?", "latency_ms": 870, "correct": False},
]
df = pd.DataFrame(rows)
print(df.to_string())
print(df.shape)                          # (number of rows, number of columns)
print(list(df.columns))

latency = df["latency_ms"]               # one column: a Series
print(type(latency).__name__)
print(latency.to_string())               # index on the left, values on the right
print(latency.mean(), latency.max())
print(df["correct"].mean())              # True counts as 1 and False as 0: this is the accuracy
Expected output
         model            question  latency_ms  correct
0  llama3.2:3b  Capital of France?         420     True
1  llama3.2:3b      What is 2 + 2?         380     True
2   qwen2.5:7b  Capital of France?         910     True
3   qwen2.5:7b      What is 2 + 2?         870    False
(4, 4)
['model', 'question', 'latency_ms', 'correct']
Series
0    420
1    380
2    910
3    870
645.0 910
0.75
JavaScript
const rows = [{ model: "llama3.2:3b", latencyMs: 420, correct: true }, /* ... */];
const latencies = rows.map((r) => r.latencyMs);
const mean = latencies.reduce((a, b) => a + b, 0) / latencies.length;
const accuracy = rows.filter((r) => r.correct).length / rows.length;
Java
record Run(String model, int latencyMs, boolean correct) {}
List<Run> rows = List.of(new Run("llama3.2:3b", 420, true) /* ... */);
double mean = rows.stream().mapToInt(Run::latencyMs).average().orElse(0);
double accuracy = rows.stream().filter(Run::correct).count() / (double) rows.size();
Python (pandas)
df = pd.DataFrame(rows)
mean = df["latency_ms"].mean()
accuracy = df["correct"].mean()

df["latency_ms"] returns the column as a Series, and .mean() and .max() work on the whole column at once: no loop. pd.set_option changes how pandas prints, never the data. to_string() always prints every row and column, which is why this lesson uses it everywhere.

Tip Think of a DataFrame as a SQL table you can query in memory, and of a Series as one column of it. You rarely loop over rows: you ask for whole columns.

2Reading CSV and JSONL

pd.read_csv(path) reads a CSV file into a DataFrame, and pd.read_json(path, lines=True) reads JSONL (also called JSON Lines: one JSON object per line), the format most eval tools and LLM log exports use. In a project you pass a file name such as "results.csv".

This page runs Python in your browser, where there are no files of yours to read, so the examples wrap a string in io.StringIO. That turns a string into a file-like object: something with a read() method, like a StringReader in Java. read_csv and read_json accept one wherever they accept a path.

Logged API responses are often nested ("usage": {"prompt_tokens": 25}). pd.json_normalize flattens a list of dicts and turns nested keys into columns named with dots, such as usage.prompt_tokens.

Try it: edit and run
import io
import json
import pandas as pd

csv_text = """id,model,category,latency_ms
1,llama3.2:3b,math,420
2,llama3.2:3b,facts,
3,qwen2.5:7b,math,910
"""
df = pd.read_csv(io.StringIO(csv_text))      # in a project: pd.read_csv("results.csv")
print(df.to_string())
print(df["latency_ms"].dtype)                # the empty cell became NaN, so the column is float

jsonl_text = """{"id": 1, "model": "llama3.2:3b", "usage": {"prompt_tokens": 25, "completion_tokens": 6}}
{"id": 2, "model": "qwen2.5:7b", "usage": {"prompt_tokens": 25, "completion_tokens": 9}}
"""
runs = pd.read_json(io.StringIO(jsonl_text), lines=True)
print(runs.to_string())                      # usage is still a dict inside one cell

records = [json.loads(line) for line in jsonl_text.splitlines()]
flat = pd.json_normalize(records)            # nested keys become columns
print(flat.to_string())
Expected output
   id        model category  latency_ms
0   1  llama3.2:3b     math       420.0
1   2  llama3.2:3b    facts         NaN
2   3   qwen2.5:7b     math       910.0
float64
   id        model                                          usage
0   1  llama3.2:3b  {'prompt_tokens': 25, 'completion_tokens': 6}
1   2   qwen2.5:7b  {'prompt_tokens': 25, 'completion_tokens': 9}
   id        model  usage.prompt_tokens  usage.completion_tokens
0   1  llama3.2:3b                   25                        6
1   2   qwen2.5:7b                   25                        9

The empty latency_ms cell became NaN ("not a number"), pandas' marker for a missing value. An integer column cannot hold NaN, so pandas made the whole column float64 and printed 420.0. json.loads(line) parses one line of JSON into a dict, and the list comprehension does that for every line; json_normalize then builds the flat table from those dicts.

Tip Writing results as JSONL (one json.dumps(record) per line, appended as each LLM call finishes) is a good habit for evals: a crash halfway through loses nothing, and pandas reads the file back with one line.

3Selecting columns and rows: [], loc, iloc and filters

df["model"] gives one column (a Series) and df[["id", "model"]], with a list inside the brackets, gives a smaller DataFrame. To pick rows there are two tools, and mixing them up is the most common pandas bug:

  • df.loc[...] selects by label: the index value and the column name. df.loc[2, "model"] is "the row labelled 2, column model". Slices with loc include the end label.
  • df.iloc[...] selects by position, like a Java or JS array: df.iloc[0] is the first row, whatever its label. Slices with iloc exclude the end, like list[0:2].

A boolean filter is a Series of True and False, one per row: df["latency_ms"] > 800 builds one. Put it inside df[...] or df.loc[...] to keep the rows where it is True. Combine conditions with & (and), | (or) and ~ (not), and wrap each condition in parentheses: and and or do not work on Series.

Try it: edit and run
import pandas as pd

df = pd.DataFrame({
    "id": [1, 2, 3, 4, 5],
    "model": ["llama3.2:3b", "llama3.2:3b", "qwen2.5:7b", "qwen2.5:7b", "qwen2.5:7b"],
    "category": ["math", "facts", "math", "facts", "code"],
    "latency_ms": [420, 380, 910, 870, 1250],
    "correct": [True, False, True, True, False],
})

print(df[["id", "model"]].to_string())
print(df.loc[2, "model"])                    # row label 2, column "model"
print(df.iloc[0].to_dict())                  # first row, as a dict

slow = df["latency_ms"] > 800                # a Series of True / False
print(slow.tolist())
print(df[slow].to_string())

wrong_qwen = df.loc[(df["model"] == "qwen2.5:7b") & ~df["correct"], ["id", "latency_ms"]]
print(wrong_qwen.to_string())

print(df[df["category"].isin(["math", "code"])]["id"].tolist())

fast = df[df["latency_ms"] < 900]            # labels 0, 1, 3 are left
print(fast.loc[3, "id"], fast.iloc[2]["id"])  # label 3 and position 2 are the same row here
Expected output
   id        model
0   1  llama3.2:3b
1   2  llama3.2:3b
2   3   qwen2.5:7b
3   4   qwen2.5:7b
4   5   qwen2.5:7b
qwen2.5:7b
{'id': 1, 'model': 'llama3.2:3b', 'category': 'math', 'latency_ms': 420, 'correct': True}
[False, False, True, True, True]
   id       model category  latency_ms  correct
2   3  qwen2.5:7b     math         910     True
3   4  qwen2.5:7b    facts         870     True
4   5  qwen2.5:7b     code        1250    False
   id  latency_ms
4   5        1250
[1, 3, 5]
4 4

A dict of lists ({"column": [values]}) is the other common way to build a DataFrame. df.loc[mask, ["id", "latency_ms"]] filters rows and picks columns in one step: rows first, columns second, like SELECT id, latency_ms ... WHERE. ~df["correct"] flips every True and False. .isin([...]) is SQL IN. A filter keeps the original labels, so after it loc[3] and iloc[3] are no longer the same row: in fast, label 3 sits at position 2.

Watch out df[df["a"] > 1 and df["b"] < 5] raises ValueError: The truth value of a Series is ambiguous. Python's and wants one True or False, not a column of them. Write df[(df["a"] > 1) & (df["b"] < 5)], with the parentheses: & binds tighter than >.

4Adding columns and handling missing data

Assigning to a new column name adds a column: df["cost_usd"] = .... The right side is usually maths on other columns, and it runs on every row at once (that is vectorised code, more on it below).

Real results have holes: a call that timed out has no answer and no latency. pandas marks those as NaN (or None in a text column). Four tools handle them: isna() finds them, fillna(value) replaces them, dropna() removes rows that have them, and most maths (mean, sum) skips them by default.

np.where(condition, a, b) from NumPy is a vectorised if / else: for each row it takes a where the condition is true and b where it is not. NumPy comes with pandas, so there is nothing more to install.

Try it: edit and run
import numpy as np
import pandas as pd

df = pd.DataFrame({
    "model": ["llama3.2:3b", "llama3.2:3b", "qwen2.5:7b", "qwen2.5:7b"],
    "answer": ["Paris", None, "Paris", "4"],
    "latency_ms": [420, np.nan, 910, 870],
    "prompt_tokens": [1200, 1180, 1200, 1150],
    "completion_tokens": [12, 0, 15, 8],
})

df["total_tokens"] = df["prompt_tokens"] + df["completion_tokens"]
df["cost_usd"] = df["total_tokens"] * 0.40 / 1_000_000       # $0.40 per million tokens
df["speed"] = np.where(df["latency_ms"] > 900, "slow", "ok")
print(df[["total_tokens", "cost_usd", "speed"]].to_string())

print(df.isna().sum().to_string())             # missing values per column
print(df["latency_ms"].mean())                 # NaN is skipped: (420 + 910 + 870) / 3

df["answer"] = df["answer"].fillna("")         # a missing answer becomes an empty string
df["timed_out"] = df["latency_ms"].isna()
done = df.dropna(subset=["latency_ms"])        # keep rows that have a latency
print(len(df), len(done))
print(df[["answer", "timed_out"]].to_string())
Expected output
   total_tokens  cost_usd speed
0          1212  0.000485    ok
1          1180  0.000472    ok
2          1215  0.000486  slow
3          1158  0.000463    ok
model                0
answer               1
latency_ms           1
prompt_tokens        0
completion_tokens    0
total_tokens         0
cost_usd             0
speed                0
733.3333333333334
4 3
  answer  timed_out
0  Paris      False
1              True
2  Paris      False
3      4      False

np.nan is how you write a missing number yourself. df.isna() is a table of True / False, and .sum() counts the True values in each column. Row 1 has NaN latency, yet np.where put ok there: NaN > 900 is False, like every <, > or == comparison with NaN. fillna and dropna return a new object, which is why the result is assigned back.

Watch out Never test for missing values with ==: np.nan == np.nan is False, so df[df["latency_ms"] == np.nan] is always empty. Use .isna() and .notna().

5Cleaning model answers with .str

Model answers are messy: " Paris.", "PARIS", "The answer is Paris!". Before you can score them you normalise them. The .str accessor gives every Python string method (and a few more) for a whole text column at once: .str.strip(), .str.lower(), .str.replace(), .str.contains(), .str.len(), .str.split().

.str.replace(pattern, "", regex=True) uses a regular expression, the same idea as String.replaceAll in Java or .replace(/.../g, "") in JavaScript. [^\w\s] means "any character that is not a letter, digit, underscore or whitespace", so it strips punctuation.

The .str methods take one pattern for the whole column. When each row has its own expected answer, compare row by row with zip, which walks two columns side by side like a Java loop over two lists with one index.

Try it: edit and run
import pandas as pd

df = pd.DataFrame({
    "expected": ["Paris", "4", "Python", "blue", "Canberra"],
    "answer": ["  Paris.", "The answer is 4", "PYTHON!", None, "Sorry, I cannot help with that."],
})


def normalise(s):
    return (
        s.fillna("")                                # a missing answer becomes ""
        .str.strip()                                # remove spaces at both ends
        .str.lower()
        .str.replace(r"[^\w\s]", "", regex=True)    # remove punctuation
    )


df["clean"] = normalise(df["answer"])
want = normalise(df["expected"])
df["exact"] = df["clean"] == want
df["contains"] = [w in c for w, c in zip(want, df["clean"])]
df["refusal"] = df["clean"].str.contains("sorry|cannot|unable")
df["length"] = df["clean"].str.len()

print(df[["clean", "exact", "contains", "refusal", "length"]].to_string())
print(f"exact: {df['exact'].mean():.0%}, contains: {df['contains'].mean():.0%}")
Expected output
                           clean  exact  contains  refusal  length
0                          paris   True      True    False       5
1                the answer is 4  False      True    False      15
2                         python   True      True    False       6
3                                 False     False    False       0
4  sorry i cannot help with that  False     False     True      29
exact: 40%, contains: 60%

The chain in normalise works because each .str method returns a new Series, so you can call the next one on it; the outer parentheses let the chain span several lines. The r before the pattern makes a raw string, so the backslashes reach the regex unchanged. str.contains("sorry|cannot|unable") is a regex too: | means "or". want is a Series you never store in the table: you can compute with any Series that has the same index. :.0% formats 0.4 as 40%.

Tip Keep the raw answer and add the cleaned one as a new column. When a score looks wrong you will want to see exactly what the model said.

Watch out "contains" scoring is generous: "12" in "120" is True. For numbers and labels, compare the cleaned answer exactly or pull the value out with a regex; for free text, use an LLM judge (the evals lab).

6groupby, aggregation and sorting

df.groupby("model") splits the rows into one group per model. Pick a column and an aggregation and you get one result per group: df.groupby("model")["correct"].mean() is accuracy per model, the same as SELECT model, AVG(correct) ... GROUP BY model.

For several numbers at once, .agg() takes named aggregations: accuracy=("correct", "mean") means "a result column called accuracy, from the correct column, using mean". Common ones: "mean", "sum", "count", "min", "max", "median".

sort_values("col", ascending=False) sorts, biggest first. Pass lists to sort on several columns: sort_values(["accuracy", "avg_latency"], ascending=[False, True]). reset_index() turns the group labels back into a normal column.

Try it: edit and run
import pandas as pd

df = pd.DataFrame({
    "model": ["llama3.2:3b"] * 4 + ["qwen2.5:7b"] * 4,
    "category": ["math", "math", "facts", "code"] * 2,
    "correct": [True, False, True, False, True, True, True, False],
    "latency_ms": [410, 520, 380, 300, 900, 980, 870, 820],
})

print(df.groupby("model")["correct"].mean().to_string())

summary = (
    df.groupby("model")
    .agg(
        n=("correct", "count"),
        accuracy=("correct", "mean"),
        avg_latency=("latency_ms", "mean"),
        max_ms=("latency_ms", "max"),
    )
    .sort_values("accuracy", ascending=False)
    .reset_index()
)
print(summary.to_string())

by_both = df.groupby(["model", "category"])["correct"].mean().reset_index()
print(by_both.sort_values(["category", "model"]).to_string(index=False))
Expected output
model
llama3.2:3b    0.50
qwen2.5:7b     0.75
         model  n  accuracy  avg_latency  max_ms
0   qwen2.5:7b  4      0.75        892.5     980
1  llama3.2:3b  4      0.50        402.5     520
      model category  correct
llama3.2:3b     code      0.0
 qwen2.5:7b     code      0.0
llama3.2:3b    facts      1.0
 qwen2.5:7b    facts      1.0
llama3.2:3b     math      0.5
 qwen2.5:7b     math      1.0

["llama3.2:3b"] * 4 repeats a list item four times, a quick way to make test data. The first result prints model on top because the group labels became the index, and the index is named after the grouped column. Grouping by a list of columns makes one group per combination. to_string(index=False) hides the row labels, which mean nothing after a sort. count counts non-missing values, so it is also a quick check for gaps.

Tip Always add a count (n=("correct", "count")) next to an average. "100% accurate" over 2 questions and over 2,000 questions are very different claims.

7merge: joining two tables

Results rarely hold everything you need. The token counts are in your eval log, but the prices are in another table. pd.merge(left, right, on="model", how="left") joins them like SQL: on is the join column and how is the join type ("inner", "left", "right", "outer").

Use how="left" to keep every result even when the other table has no match: the missing columns become NaN, which you can then find with isna(). validate="many_to_one" makes pandas raise an error if the price table has the same model twice, which would quietly duplicate your rows.

Try it: edit and run
import pandas as pd

results = pd.DataFrame({
    "id": [1, 2, 3, 4],
    "model": ["llama3.2:3b", "qwen2.5:7b", "qwen2.5:7b", "mistral:7b"],
    "prompt_tokens": [1200, 1200, 1150, 1100],
    "completion_tokens": [12, 15, 8, 20],
})
prices = pd.DataFrame({
    "model": ["llama3.2:3b", "qwen2.5:7b"],
    "input_per_m": [0.10, 0.40],     # dollars per million input tokens
    "output_per_m": [0.10, 1.20],    # dollars per million output tokens
})

df = pd.merge(results, prices, on="model", how="left", validate="many_to_one")
df["cost_usd"] = (
    df["prompt_tokens"] * df["input_per_m"] + df["completion_tokens"] * df["output_per_m"]
) / 1_000_000
print(df.to_string())

unpriced = df.loc[df["input_per_m"].isna(), "model"].unique().tolist()
print("no price for:", unpriced)
print(len(pd.merge(results, prices, on="model")))    # inner join: mistral is dropped
Expected output
   id        model  prompt_tokens  completion_tokens  input_per_m  output_per_m  cost_usd
0   1  llama3.2:3b           1200                 12          0.1           0.1  0.000121
1   2   qwen2.5:7b           1200                 15          0.4           1.2  0.000498
2   3   qwen2.5:7b           1150                  8          0.4           1.2  0.000470
3   4   mistral:7b           1100                 20          NaN           NaN       NaN
no price for: ['mistral:7b']
3

The merge copied the right price onto every matching row; mistral:7b has no price, so its price columns and its cost are NaN instead of a wrong number. .unique() lists each value once. Without how=, merge does an inner join and silently drops the unmatched row, which here would hide a model from your cost report.

Tip After every merge, check that the row count is what you expect (len(df)). A duplicated key on the right side multiplies rows, and every total after it is wrong.

8apply versus vectorised code

df.apply(fn, axis=1) calls a Python function once per row: it feels like a for loop or a JS map, and it is just as slow, because each call is ordinary Python. Vectorised code (df["a"] * 0.15 + df["b"]) hands the whole column to NumPy, which runs the loop in compiled C code.

The example computes the cost of 50,000 calls both ways and times them with time.perf_counter(). Expect the vectorised version to be hundreds of times faster. The exact times change from run to run, so the code prints only whether the results match and whether the gap is big.

Try it: edit and run
import time
import numpy as np
import pandas as pd

n = 50_000
df = pd.DataFrame({
    "prompt_tokens": np.arange(n) % 2000 + 100,      # 100, 101, ... made-up token counts
    "completion_tokens": np.arange(n) % 300 + 10,
})

start = time.perf_counter()
slow = df.apply(
    lambda row: (row["prompt_tokens"] * 0.15 + row["completion_tokens"] * 0.60) / 1_000_000,
    axis=1,                                           # call the function once per row
)
t_apply = time.perf_counter() - start

start = time.perf_counter()
fast = (df["prompt_tokens"] * 0.15 + df["completion_tokens"] * 0.60) / 1_000_000
t_vector = time.perf_counter() - start

print("same result:", bool(np.allclose(slow, fast)))
print("vectorised at least 10x faster:", t_apply > 10 * t_vector)
Expected output
same result: True
vectorised at least 10x faster: True

np.arange(n) is 0, 1, 2, ... n-1, and % 2000 + 100 turns it into varied but repeatable test data. lambda row: ... is a one-line anonymous function, like row -> ... in Java or (row) => ... in JS; with axis=1 pandas passes it one row at a time as a Series. np.allclose compares two columns of floats allowing for tiny rounding differences. Print t_apply and t_vector yourself to see the real times.

Tip Use apply (or a list comprehension with zip, as in the .str section) only for logic NumPy cannot express, such as calling a tokenizer or a scoring function per answer. For maths, comparisons and text cleaning, use column operations, np.where and .str.

9Build an eval report from LLM results

Now everything together. You ran 6 questions through two models and logged one JSON line per answer. The script loads the log, joins prices, scores each answer, and prints the report you would paste into a pull request: accuracy per category, accuracy, latency and cost per model, a pivot table of model against category, and the worst cases.

pivot_table(index="model", columns="category", values="correct", aggfunc="mean") is a groupby on two columns laid out as a grid: one row per model, one column per category, the mean of correct in each cell. It is the Excel pivot table.

In a .py file you would end with if __name__ == "__main__": main(), so main() runs when you start the file and not when a test imports it. Code on this page runs with __name__ set to "builtins", so the guard would skip main() here; the box calls main() directly.

Try it: edit and run
import io
import pandas as pd

LOG = """{"id": 1, "model": "llama3.2:3b", "category": "math", "expected": "36", "answer": " 36", "latency_ms": 410, "prompt_tokens": 1200, "completion_tokens": 4}
{"id": 2, "model": "llama3.2:3b", "category": "math", "expected": "12", "answer": "15% of 80 is 12.", "latency_ms": 520, "prompt_tokens": 1210, "completion_tokens": 9}
{"id": 3, "model": "llama3.2:3b", "category": "facts", "expected": "Canberra", "answer": "Sydney", "latency_ms": 380, "prompt_tokens": 1190, "completion_tokens": 3}
{"id": 4, "model": "llama3.2:3b", "category": "facts", "expected": "Shakespeare", "answer": "William Shakespeare.", "latency_ms": 450, "prompt_tokens": 1180, "completion_tokens": 5}
{"id": 5, "model": "llama3.2:3b", "category": "code", "expected": "yield", "answer": "YIELD", "latency_ms": 300, "prompt_tokens": 1205, "completion_tokens": 2}
{"id": 6, "model": "llama3.2:3b", "category": "code", "expected": "append", "answer": null, "latency_ms": 30000, "prompt_tokens": 1200, "completion_tokens": 0}
{"id": 1, "model": "qwen2.5:7b", "category": "math", "expected": "36", "answer": "36", "latency_ms": 900, "prompt_tokens": 1200, "completion_tokens": 2}
{"id": 2, "model": "qwen2.5:7b", "category": "math", "expected": "12", "answer": "12", "latency_ms": 980, "prompt_tokens": 1210, "completion_tokens": 2}
{"id": 3, "model": "qwen2.5:7b", "category": "facts", "expected": "Canberra", "answer": "Canberra.", "latency_ms": 870, "prompt_tokens": 1190, "completion_tokens": 4}
{"id": 4, "model": "qwen2.5:7b", "category": "facts", "expected": "Shakespeare", "answer": "Christopher Marlowe", "latency_ms": 940, "prompt_tokens": 1180, "completion_tokens": 6}
{"id": 5, "model": "qwen2.5:7b", "category": "code", "expected": "yield", "answer": "yield", "latency_ms": 820, "prompt_tokens": 1205, "completion_tokens": 2}
{"id": 6, "model": "qwen2.5:7b", "category": "code", "expected": "append", "answer": "list.append()", "latency_ms": 1100, "prompt_tokens": 1200, "completion_tokens": 6}
"""
PRICES = pd.DataFrame({
    "model": ["llama3.2:3b", "qwen2.5:7b"],
    "input_per_m": [0.10, 0.40],
    "output_per_m": [0.10, 1.20],
})


def normalise(s):
    return s.fillna("").str.strip().str.lower().str.replace(r"[^\w\s]", "", regex=True)


def load(text):
    df = pd.read_json(io.StringIO(text), lines=True)
    df = pd.merge(df, PRICES, on="model", how="left", validate="many_to_one")
    clean, want = normalise(df["answer"]), normalise(df["expected"])
    df["correct"] = [w in c for w, c in zip(want, clean)]
    df["cost_usd"] = (df["prompt_tokens"] * df["input_per_m"]
                      + df["completion_tokens"] * df["output_per_m"]) / 1_000_000
    return df


def report(df):
    per_category = df.groupby("category")["correct"].mean().round(2)
    per_model = (
        df.groupby("model")
        .agg(n=("id", "count"), accuracy=("correct", "mean"),
             median_ms=("latency_ms", "median"), cost_per_1k=("cost_usd", "mean"))
        .assign(cost_per_1k=lambda t: t["cost_per_1k"] * 1000)   # dollars per 1,000 calls
        .round({"accuracy": 2, "cost_per_1k": 3})
    )
    grid = df.pivot_table(index="model", columns="category", values="correct", aggfunc="mean")
    worst = (df[~df["correct"]]
             .sort_values("latency_ms", ascending=False)
             [["model", "id", "expected", "latency_ms"]])
    return per_category, per_model, grid.round(2), worst


def main():
    df = load(LOG)
    per_category, per_model, grid, worst = report(df)
    print("== accuracy per category ==")
    print(per_category.to_string())
    print("== per model ==")
    print(per_model.to_string())
    print("== model x category ==")
    print(grid.to_string())
    print("== worst cases ==")
    print(worst.to_string(index=False))
    print("== csv ==")
    print(per_model.to_csv(), end="")


main()   # in a .py file: if __name__ == "__main__": main()
Expected output
== accuracy per category ==
category
code     0.75
facts    0.50
math     1.00
== per model ==
             n  accuracy  median_ms  cost_per_1k
model                                           
llama3.2:3b  6      0.67      430.0        0.120
qwen2.5:7b   6      0.83      920.0        0.483
== model x category ==
category     code  facts  math
model                         
llama3.2:3b   0.5    0.5   1.0
qwen2.5:7b    1.0    0.5   1.0
== worst cases ==
      model  id    expected  latency_ms
llama3.2:3b   6      append       30000
 qwen2.5:7b   4 Shakespeare         940
llama3.2:3b   3    Canberra         380
== csv ==
model,n,accuracy,median_ms,cost_per_1k
llama3.2:3b,6,0.67,430.0,0.12
qwen2.5:7b,6,0.83,920.0,0.483

load does the reading, joining and scoring, and report only summarises: keep the two apart so you can test each one. .assign(cost_per_1k=lambda t: ...) replaces a column inside a chain; t is the table at that point of the chain. .round({...}) rounds each named column to its own number of decimals. The median latency is used because one 30 second timeout would wreck an average. The worst cases are the wrong answers, slowest first: the timeout tops the list, which is exactly what you want to look at first. to_csv() with no file name returns the CSV as a string; per_model.to_csv("report.csv") writes a file.

Markdown for a pull request. per_model.to_markdown() returns the same table as Markdown. pandas needs the small tabulate package for it, which the browser does not have, so try it in a project: run uv add pandas tabulate, add print(per_model.to_markdown()) at the end of main(), and run the file with uv run python report.py. It prints:

| model       |   n |   accuracy |   median_ms |   cost_per_1k |
|:------------|----:|-----------:|------------:|--------------:|
| llama3.2:3b |   6 |       0.67 |         430 |         0.12  |
| qwen2.5:7b  |   6 |       0.83 |         920 |         0.483 |

Without tabulate it raises ImportError: Missing optional dependency 'tabulate'. In GitHub Actions, append that text to the file named by $GITHUB_STEP_SUMMARY and the table appears on the run page.

Tip qwen2.5:7b answers one more question right, but costs four times as much per call and takes twice as long, and llama3.2:3b only lost one of its points to a timeout. That is the kind of trade-off an eval report should make obvious. Save each run's report with the model, prompt version and date, and compare runs before you change a prompt or a model.

Common mistakes

  • Using and / or between conditions (df[a > 1 and b < 2]): use & / | and wrap each condition in parentheses.
  • Mixing up loc (labels) and iloc (positions). After a filter or a sort the labels are no longer 0, 1, 2, so df.loc[0] may not be the first row, or may not exist.
  • Testing for missing values with == np.nan, which is always False. Use .isna().
  • Calling fillna, dropna, sort_values or merge and not assigning the result: they return a new DataFrame and leave the original unchanged.
  • Merging with the default inner join and losing rows that had no match, or merging on a key that is duplicated on the right and silently multiplying rows. Use how="left", validate= and check len(df).
  • Looping over rows with apply(axis=1) or iterrows() for plain maths. Use column operations: they are hundreds of times faster.

Practice

Write the code, then press Check. Your work is saved in this browser.

1Clean the answers

Write clean(s) that takes a Series of model answers and returns a new Series where missing answers are "", spaces at both ends are removed, the text is lower case, and a trailing ., ! or ? is removed (punctuation in the middle stays).

Exercise
import pandas as pd


def clean(s):
    # your code here
    return s


print(clean(pd.Series(["  Paris.", "YES!", None, "3.14"])).tolist())
Hint

Chain `.fillna("")`, `.str.strip()`, `.str.lower()` and `.str.replace(r"[.!?]$", "", regex=True)`. `$` means "at the end".

2Accuracy table

Write accuracy_by(df, column) that returns a DataFrame with one row per value of column, a normal column with that name, and two more columns: n (number of rows) and accuracy (mean of correct, rounded to 2 decimals). Sort by accuracy, highest first; break ties by column, A to Z. The row labels must be 0, 1, 2 and so on.

Exercise
import pandas as pd


def accuracy_by(df, column):
    # your code here
    return df


df = pd.DataFrame({"model": ["a", "a", "b", "b", "b"], "correct": [True, False, True, True, False]})
print(accuracy_by(df, "model").to_string())
Hint

`df.groupby(column).agg(n=("correct", "count"), accuracy=("correct", "mean")).reset_index()`, then `.round({"accuracy": 2})`, then `sort_values(["accuracy", column], ascending=[False, True])` and `reset_index(drop=True)`.

3Worst cases with a price join

Write worst_cases(results, prices, n). Join prices (columns model, per_m: dollars per million tokens) onto results (columns id, model, tokens, correct) keeping every result, add cost_usd = tokens * per_m / 1_000_000, and return the n wrong answers with the highest cost, most expensive first, with only the columns id, model and cost_usd. A model with no price must not crash the function (its cost is missing and it goes last).

Exercise
import pandas as pd


def worst_cases(results, prices, n):
    # your code here
    return results
Hint

`pd.merge(results, prices, on="model", how="left")`, add the column, filter with `~df["correct"]`, then `sort_values("cost_usd", ascending=False)` (missing values go last by default) and `.head(n)[["id", "model", "cost_usd"]]`.

Interview questions

Q1What is the difference between a Series and a DataFrame?

A Series is one labelled column of values of one type, with an index. A DataFrame is a table of Series that share the same index, one per named column. Selecting one column of a DataFrame gives a Series; selecting a list of columns gives a DataFrame.

Q2What is the difference between loc and iloc?

loc selects by label (index values and column names) and its slices include the end label. iloc selects by integer position and its slices exclude the end, like Python lists. They give the same result only while the index is still 0, 1, 2 in order; after a filter or sort they differ.

Q3How do you handle missing data in pandas?

Find it with isna() (counts with isna().sum()), then decide per column: drop rows with dropna(subset=[...]), fill with fillna(value), or keep it and let aggregations skip it, which they do by default. Missing numbers force an integer column to float. Never compare with == np.nan.

Q4Why is vectorised code faster than apply or iterrows?

Vectorised operations run one loop over the whole column in compiled NumPy code. apply(axis=1) and iterrows call Python code once per row and build a Series for each, so they are usually one to three orders of magnitude slower. Use apply only for logic that cannot be written with column operations.

Q5How would you build an evaluation report for two LLMs?

Log one JSON line per question and model with the expected answer, the output, latency and token counts. Load it with read_json(lines=True), normalise answers and score them, join a price table, then groupby("model") for accuracy, count, median latency and cost, a pivot_table of model against category, and a list of failures sorted by severity. Export to CSV or Markdown and compare against the previous run.

Q6What can go wrong with a merge?

An inner join silently drops unmatched rows, and a duplicated key on either side multiplies rows so totals are inflated. Use how="left" when every row must survive, validate="many_to_one" (or one_to_one) to fail fast on duplicate keys, and check the row count and the NaNs in the joined columns.