g↗genai/ learner
Python for AI / Lesson 12

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.

Concept + interactive labBeginner friendly

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:

  1. DataFrame: A two-dimensional table in pandas with labeled rows (its index) and named columns.
  2. Series: A one-dimensional labeled sequence, such as a single column taken from a DataFrame.
  3. Column lookup (df["col"]): Selecting a column by its string label (column name) inside square brackets.
  4. 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.
  5. Accumulator loop: A Python for loop 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
Infographic titled From dictionary to DataFrame: Equal-length lists become a 2D table in Python memory. A Dictionary card with prompt_id, model, and tokens flows right through pd.DataFrame(data) into a DataFrame table with Index 0 through 4 and rows p1 gemini 10, p2 gemini 20, p3 claude 30, p4 gpt 15, and p5 claude 25. Bottom strip reads Everyday analogy: Like a spreadsheet table in Python memory.
A DataFrame aligns named vertical columns with numbered horizontal row labels (0 to 4 in this example).
✎ Try it yourselfKnowledge check · Practice only

Quick check: Understanding the DataFrame structure

In the example above, what does pd.DataFrame(data) create in memory?

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: int64

The 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).
Selecting df["tokens"] extracts the column as a 1D Series with its row index intact.
✎ Try it yourselfKnowledge check · Practice only

Quick check: Column selection syntax

In a fresh script with no variable named tokens, which expression selects the 'tokens' column from df?

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.0

Both 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.
Calling df["tokens"].sum() replaces manual accumulator bookkeeping with a single column method call.

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())
✎ Try it yourselfKnowledge check · Practice only

Practice: What does this line print?

Given tokens [10, 20, 30, 15, 25], what does print(df['tokens'].mean()) output?

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:

  1. Leave Approach on pandas 1-step call. Toggle between .sum() (100) and .mean() (20.0) to see the column evaluated in a single call.
  2. 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.
  3. 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.
Approach:
Operation:
Prompt evaluation dataset with prompt ID, model, and tokens
Indexprompt_idmodeltokens (selected Series)
0p1gemini10
1p2gemini20
2p3claude30
3p4gpt15
4p5claude25
df["tokens"].sum() → 100

pandas processes all 5 token values in one direct call, returning the total 100 without manual loop code.

✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

Why do AI engineers often use df['tokens'].sum() instead of writing a manual for loop to total a column?

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 at 0 by 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() and df["col"].mean() return a summary number without modifying df.
  • Less boilerplate: Column methods replace manual accumulator for loops 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.