Introduction to pandas
pandas organizes structured data into a 2D table of rows and columns called a DataFrame, letting you calculate whole-column totals and averages in one call without writing manual for loops.
pandas: Turning structured data into tables for instant analysis.
In AI work, you often inspect batches of prompts, model names, and token counts. Plain Python lists and dictionaries can store those values, but summarizing them usually means writing a for loop by hand.
The pandas library adds table structures so you can select and summarize a whole column in one line. In this lesson, you will meet these terms in order:
- DataFrame: A two-dimensional table in pandas with labeled rows (its index) and named columns.
- Series: A one-dimensional labeled sequence, such as a single column taken from a DataFrame.
- Column lookup (
df["col"]): Selecting a column by its string label (column name) inside square brackets. - Column aggregation method: A built-in method (a function attached to an object, called with a dot) such as
.sum()or.mean()that summarizes a column's values. - Accumulator loop: A Python
forloop that visits values one by one to build a running total in a variable.
Note: pandas is a third-party library, not part of Python's standard library. On your own machine or notebook, install it once with pip install pandas before importing it.
A DataFrame organizes records into rows and columns.
Think of a spreadsheet of customer orders: each horizontal row is one order, and each vertical column is one field such as Customer, Size, or Price. A pandas DataFrame organizes data the same way, except it lives in Python memory rather than creating a spreadsheet file on disk.
To build one, import pandas (by wide convention aliased as pd) and pass a dictionary of equal-length lists to pd.DataFrame(). In this illustrative 5-row prompt log, each dictionary key becomes a column name and each list provides the row values:
import pandas as pd
data = {
"prompt_id": ["p1", "p2", "p3", "p4", "p5"],
"model": ["gemini", "gemini", "claude", "gpt", "claude"],
"tokens": [10, 20, 30, 15, 25],
}
df = pd.DataFrame(data)
print(df)Printing df displays the 2D table with default row labels (0 through 4) on the left — called the index:
prompt_id model tokens
0 p1 gemini 10
1 p2 gemini 20
2 p3 claude 30
3 p4 gpt 15
4 p5 claude 25
Quick check: Understanding the DataFrame structure
Selecting a column gives you a pandas Series.
To work with one field across all rows, put its string label inside square brackets: df["tokens"].
In a DataFrame with unique column names like this one, selecting one column returns a pandas Series — a 1D labeled sequence that keeps each value paired with its row index:
tokens_series = df["tokens"]
print(tokens_series)0 10
1 20
2 30
3 15
4 25
Name: tokens, dtype: int64The footer shows the column's name and its dtype (data type — here int64, a 64-bit integer; the exact integer dtype can vary by platform or pandas version).
Quotes matter here: df["tokens"] passes the string label "tokens". If you write df[tokens] without quotes in a fresh script where no variable named tokens exists, Python raises a NameError.
Everyday analogy: if a restaurant ledger lists Order Number, Server, and Amount, selecting df["Amount"] pulls out just the Amount column while keeping each row's position lined up.
![Infographic titled Select one column to get a Series: Use quotes around the column name to keep index and values paired. A DataFrame with prompt_id, model, and highlighted tokens column flows right via df['tokens'] into a 1D Series with Index 0 to 4 and Values 10, 20, 30, 15, and 25. Bottom cards compare df['tokens'] (Selects the column) against df[tokens] (NameError, missing quotes).](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Fcolumn-series.25b32bktf0m_1.webp&w=3840&q=75)
Quick check: Column selection syntax
Column methods replace manual for loops.
Once you select a numeric column like df["tokens"], you can call built-in aggregation methods such as .sum() and .mean() directly on it.
Compare a manual Python accumulator loop (which totals the five values and then divides by the row count for the average) with pandas:
# Approach A: Manual for loop + division for the mean
total = 0
for t in data["tokens"]:
total += t
average = total / len(data["tokens"])
print(total) # 100
print(average) # 20.0# Approach B: pandas column methods
print(df["tokens"].sum()) # 100
print(df["tokens"].mean()) # 20.0Both approaches compute the same numbers (100 and 20.0). With pandas, you state what summary you want in one call instead of initializing and updating a running total variable.
Everyday analogy: it is like clicking AutoSum on a spreadsheet column instead of tapping each cell into a pocket calculator — the math is the same, with less manual bookkeeping.
![Infographic titled Column method vs manual loop: Same result (100), without writing an accumulator loop. Top Manual loop card flows left to right from a 5-row column stack through total = 0 and Add each value to 100. Bottom pandas card flows left to right from the column stack through df['tokens'].sum() to Result: 100. Bottom Key takeaway strip reads Returns 100 and leaves df unchanged.](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Floop-vs-pandas.2_nly2filc1u2.webp&w=3840&q=75)
Quick Questions
- Does df["tokens"].sum() modify df?
- No. On this numeric Series, it returns a single summary number (
100) and leaves the DataFrame unchanged. - What does df["tokens"].mean() calculate?
- In this example, it returns the arithmetic average: the sum of the five values divided by the count (
100 / 5 = 20.0). - Can you still write a Python for loop when using pandas?
- Yes, normal Python loops still work, though built-in column methods are usually clearer and often faster on larger tables.
Practice: Predict the column calculation.
Use our 5-row prompt log to predict what this line prints.
# df has 5 rows with tokens: [10, 20, 30, 15, 25]
print(df["tokens"].mean())Practice: What does this line print?
Try the Prompt Log Analyzer.
Use this toy simulator to compare a single pandas column call against stepping through the same 5 rows with a manual accumulator loop.
Interactive Lab: Prompt Log Analyzer
Toy simulator with illustrative values. Compares explicit loop steps against a single pandas column call without running a live Python runtime.
Try it in this order:
- Leave Approach on pandas 1-step call. Toggle between .sum() (100) and .mean() (20.0) to see the column evaluated in a single call.
- Switch Approach to Manual loop walkthrough with .sum() selected. Click Start loop →, then Next step four more times to watch the accumulator update row by row.
- Switch Operation to .mean() while in loop mode. Step through all 5 rows, then click Divide total by count → to see the extra division step.
| Index | prompt_id | model | tokens (selected Series) |
|---|---|---|---|
| 0 | p1 | gemini | 10 |
| 1 | p2 | gemini | 20 |
| 2 | p3 | claude | 30 |
| 3 | p4 | gpt | 15 |
| 4 | p5 | claude | 25 |
df["tokens"].sum() → 100pandas processes all 5 token values in one direct call, returning the total 100 without manual loop code.
Check your understanding.
Take this with you.
Summary Cheat-Sheet
- Common convention: Import pandas as
import pandas as pd. - DataFrame: A 2D in-memory table created with
pd.DataFrame(data)from a dictionary of equal-length lists, with row index labels starting at0by default. - Column lookup:
df["column_name"]selects one column (as a 1D pandas Series when column names are unique). - Column summaries: On a numeric Series,
df["col"].sum()anddf["col"].mean()return a summary number without modifyingdf. - Less boilerplate: Column methods replace manual accumulator
forloops with a single readable call.
In the next lesson (P1.13 Columns and tables), you will build on DataFrames and Series to inspect and work with multiple columns.