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

Quick check: Reading df.shape
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 250Look 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.](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Fselect-columns.43-0k_x91r-s6.webp&w=3840&q=75)
Quick check: Multi-column selection syntax
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 300pandas 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).](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Fderived-column.0_q4s5cklm2vh.webp&w=3840&q=75)
Quick Questions
- Does
df[["model", "in_tokens"]]remove the other columns fromdf? - No. Selecting columns returns a new 2D DataFrame with just those columns and leaves
dfunchanged. - What happens if you assign to an existing column name, like
df["out_tokens"] = ...? - pandas replaces the values in
out_tokensin 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 insidedf[...]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)Practice: 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:
- Start with model and in_tokens selected. Notice the double brackets, the (5, 2) result shape, and that
df.shapestays (5, 3). - 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).
- Click Add total_tokens column to run
df["total_tokens"] = df["in_tokens"] + df["out_tokens"]and watchdf.shapechange from (5, 3) to (5, 4).
| Index | model | in_tokens |
|---|---|---|
| 0 | gemini | 100 |
| 1 | claude | 200 |
| 2 | gpt | 150 |
| 3 | gemini | 300 |
| 4 | claude | 250 |
df[["model", "in_tokens"]]Passing a Python list of 2 column names returns a 2D DataFrame of shape (5, 2). Original df stays (5, 3).
Check your understanding.
Take this with you.
Summary Cheat-Sheet
- Inspect first:
df.shapereturns(rows, columns)anddf.columnslists column labels (both attributes, no());df.head(n)is a method (uses()) that previews the firstnrows. - 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 modifyingdf. - Derived columns:
df["total_tokens"] = df["in_tokens"] + df["out_tokens"]computes row-by-row values by index and updatesdfin place.
In the next lesson (P1.14 Filtering rows), you will use conditions to keep only the rows that match your criteria.