g↗genai/ learner
Python for AI / Lesson 13

Columns and tables

Inspect a DataFrame's shape, columns, and first rows, select multiple columns as a 2D table, and create new derived columns without writing a manual loop.

Concept + interactive labBeginner friendly

Working with columns and table structure in pandas.

In Lesson 12, you built a pandas DataFrame and summarized a single column. In real AI logs, you first check a table's size and headers, pull out the subset of columns you need, and compute new columns such as total tokens.

In this lesson, you will meet five ideas in order:

  1. Attribute vs. method: An attribute (such as df.shape or df.columns) is a stored property accessed without parentheses; a method (such as df.head(2)) is an action called with parentheses.
  2. Table shape (df.shape): A (rows, columns) pair telling you how many rows and columns a DataFrame has.
  3. Multi-column selection (df[["col1", "col2"]]): Passing a Python list of column names inside df[...] to get a new 2D DataFrame containing only those columns.
  4. Derived column: A new column calculated row by row from existing columns (for example, adding input and output tokens).
  5. In-place assignment: Assigning to df["new_col"] = ... modifies df directly by adding (or overwriting) that column, whereas selecting columns leaves df unchanged.

Inspect a table's shape, columns, and first rows.

Everyday analogy: before editing a printed expense ledger, you glance at how many rows and columns it has, read the column headers, and peek at the top two lines. In pandas, three quick checks do the same job.

We will use this illustrative 5-row AI API log throughout the lesson:

import pandas as pd

data = {
    "model": ["gemini", "claude", "gpt", "gemini", "claude"],
    "in_tokens": [100, 200, 150, 300, 250],
    "out_tokens": [50, 100, 50, 100, 50],
}

df = pd.DataFrame(data)

Check the table's dimensions with df.shape, its column labels with df.columns, and a top-row preview with df.head(2):

print(df.shape)    # (5, 3)  -> 5 rows, 3 columns
print(df.columns)  # Index(['model', 'in_tokens', 'out_tokens'], ...)
print(df.head(2))  # First 2 rows (index 0 and 1)

Notice the parentheses rule. Both df.shape and df.columns are attributes (no ()): writing df.shape() raises a TypeError because a tuple is not callable. By contrast, df.head(2) is a method (uses (); calling df.head() with no argument returns up to the first 5 rows).

Note that df.columns returns a pandas Index object rather than a plain Python list (and its printed dtype label can vary by pandas version). If you need a plain Python list of names, wrap it with list(df.columns).

Infographic titled Inspecting a DataFrame: Check size, column names, and a quick preview. A 5-row DataFrame (df) with Index 0 to 4 and columns model, in_tokens, and out_tokens flows right to three cards: df.shape showing (5, 3), df.columns showing model, in_tokens, out_tokens, and df.head(2) showing Rows 0 and 1. Bottom strip reads Attribute vs. method: No () for shape and columns, Use () for head(2).
Use attributes (df.shape, df.columns) without parentheses and the df.head(n) method with parentheses to inspect a table before changing it.
✎ Try it yourselfKnowledge check · Practice only

Quick check: Reading df.shape

For a DataFrame with 5 rows and 3 columns, what does df.shape return?

Select one column for a Series, or a list for a DataFrame.

Everyday analogy: pulling a single receipt slip out of a folder gives you one 1D strip of numbers, whereas photocopying two columns onto a smaller sheet still gives you a 2D table.

In pandas (when column names are unique, as in our table), passing one string label returns a 1D Series, while passing a Python list of column labels returns a 2D DataFrame:

# One string label -> 1D Series (shape: (5,))
in_only = df["in_tokens"]

# A Python list of labels -> 2D DataFrame (shape: (5, 2))
subset = df[["model", "in_tokens"]]
print(subset)
    model  in_tokens
0  gemini        100
1  claude        200
2     gpt        150
3  gemini        300
4  claude        250

Look closely at the double square brackets in df[["model", "in_tokens"]]. The outer brackets belong to df[...]; the inner brackets are a normal Python list ["model", "in_tokens"]. Even a 1-item list like df[["in_tokens"]] returns a 2D DataFrame with shape (5, 1) rather than a 1D Series.

A common beginner mistake is dropping the inner brackets and writing df["model", "in_tokens"]. Python treats the comma-separated strings as a single tuple key ("model", "in_tokens"), and because no column in df has that tuple label, pandas raises a KeyError.

Selecting columns returns a new DataFrame selection in the column order you list and leaves the original df unchanged.

Infographic titled One column vs. multiple columns: Single brackets return a Series; a list returns a DataFrame. The center 5-row DataFrame (df) points left to a 1D Series card for df['in_tokens'] (100, 200, 150, 300, 250) and right to a 2D DataFrame card for df[['model', 'in_tokens']]. Bottom strip contrasts df[['model', 'in_tokens']] — Valid list against df['model', 'in_tokens'] — KeyError.
Single brackets with one label return a 1D Series; double brackets pass a Python list and return a 2D DataFrame.
✎ Try it yourselfKnowledge check · Practice only

Quick check: Multi-column selection syntax

You want a new 2D DataFrame containing only 'model' and 'out_tokens' from df. Which expression works?

Create a derived column from existing columns.

Everyday analogy: on an invoice sheet with Subtotal and Tax columns, you add a Total column at the right edge where each row equals Subtotal plus Tax on that same line.

In pandas, you can add two numeric columns in one expression and assign the result to a new column name on df:

df["total_tokens"] = df["in_tokens"] + df["out_tokens"]
print(df)
print(df.shape)  # (5, 4)
    model  in_tokens  out_tokens  total_tokens
0  gemini        100          50           150
1  claude        200         100           300
2     gpt        150          50           200
3  gemini        300         100           400
4  claude        250          50           300

pandas pairs values row by row using their matching row index (row 0: 100 + 50 = 150, row 1: 200 + 100 = 300, and so on) with no manual for loop.

Unlike selecting columns, assigning to df["total_tokens"] = ... modifies df in place: it attaches total_tokens to the table so df.shape grows from (5, 3) to (5, 4). If you assign to a column name that already exists, pandas overwrites that column's values.

Infographic titled Creating a derived column: Add two columns row by row and attach the result to df. Existing columns in_tokens (100, 200, 150, 300, 250) plus out_tokens (50, 100, 50, 100, 50) flow right through df['total_tokens'] = df['in_tokens'] + df['out_tokens'] into the Updated DataFrame (df) with a highlighted total_tokens column (150, 300, 200, 400, 300). Bottom strip reads In-place update: df.shape changes from (5, 3) to (5, 4).
Column arithmetic aligns rows automatically by index, and column assignment adds the new column to df in place.

Quick Questions

Does df[["model", "in_tokens"]] remove the other columns from df?
No. Selecting columns returns a new 2D DataFrame with just those columns and leaves df unchanged.
What happens if you assign to an existing column name, like df["out_tokens"] = ...?
pandas replaces the values in out_tokens in place instead of creating a second column with the same name.
What does df[["in_tokens"]] (a 1-item list) return?
A 2D DataFrame with shape (5, 1), because passing a list inside df[...] returns a DataFrame rather than a 1D Series.

Practice: Predict the shape and result.

Trace these three lines starting from the 5-row, 3-column df (model, in_tokens, out_tokens).

# Starting from the 5-row, 3-column df
df["total_tokens"] = df["in_tokens"] + df["out_tokens"]
subset = df[["model", "total_tokens"]]
print(subset.shape)
✎ Try it yourselfKnowledge check · Practice only

Practice: What does print(subset.shape) output?

Starting from the 5-row, 3-column df above, what does print(subset.shape) output?

Try the Column & Table Workbench.

Explore how selecting one column, selecting a list of columns, and assigning a derived column affect the returned object and df.shape.

Interactive Lab: Column & Table Workbench

Toy simulator with illustrative values. Shows how pandas column selection and derived-column assignment change the returned object and df.shape without running a live Python runtime.

Try it in this order:

  1. Start with model and in_tokens selected. Notice the double brackets, the (5, 2) result shape, and that df.shape stays (5, 3).
  2. Click model to deselect it so only in_tokens remains. Toggle Bracket style between single brackets (1D Series) and a 1-item list (2D DataFrame).
  3. Click Add total_tokens column to run df["total_tokens"] = df["in_tokens"] + df["out_tokens"] and watch df.shape change from (5, 3) to (5, 4).
1. Select columns:
2. Derived column:
Selected DataFrame (2D) from the AI API usage table
Indexmodelin_tokens
0gemini100
1claude200
2gpt150
3gemini300
4claude250
df[["model", "in_tokens"]]
Result: DataFrame (2D)Result shape: (5, 2)Original df.shape: (5, 3)

Passing a Python list of 2 column names returns a 2D DataFrame of shape (5, 2). Original df stays (5, 3).

✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

You have a DataFrame df with columns "model", "in_tokens", and "out_tokens". What happens when you run df["model", "in_tokens"]?

Take this with you.

Summary Cheat-Sheet

  • Inspect first: df.shape returns (rows, columns) and df.columns lists column labels (both attributes, no ()); df.head(n) is a method (uses ()) that previews the first n rows.
  • One column vs. list: df["col"] returns a 1D Series (for unique column names); df[["col1", "col2"]] passes a Python list and returns a 2D DataFrame without modifying df.
  • Derived columns: df["total_tokens"] = df["in_tokens"] + df["out_tokens"] computes row-by-row values by index and updates df in place.

In the next lesson (P1.14 Filtering rows), you will use conditions to keep only the rows that match your criteria.