Chapter 3 — pandas: “A Bear in the Archive II”

How a DataFrame Works: Rows, Columns, Series, and the Index

16 min

The Bear in the Archive

The year is 2184. You're at Vault-9, in the digital archaeology section. In front of you is Kotomarket's black box: the cat-supplies marketplace is gone, but its data remains. Its delivery cities are Furrville, Catford, Meowfield, and Tailford; its currency is $. You're the analyst-investigator. Your job is to extract an explanation of what happened here from the dead data, rather than simply write code.

In Chapter 2, you already worked through this archive by hand: lists, dictionaries, a loop, and manually accumulating totals by city. It worked. Slowly.

QUERY, the archive's duty AI: “Nine lines of code to add up amounts for four cities. The Bear does it in one. I measured. Repeatedly.”

A cadet studies a black box while a hologram above it shows a table of rows and columns, its index, and a separate Series column. A robot cat watches from the side.
A pandas table is a set of columns sharing one index: the index keeps rows aligned instead of simply numbering them in sequence.

The “Bear” is pandas: a library for working with tables. Its name comes from the term panel data, but the paw in the logo is there for a reason, and the archive never calls it anything else.

The line where everything starts

import pandas as pd

Take it apart word by word. You saw import in Chapter 2; here it has one extra piece:

  • import pandas — “load the pandas library so I can use it”;
  • as pd — “and I'll refer to it by the short name pd”.

This isn't magic: import pandas as panda would work too, and the calculations would be exactly the same. But pd is the standard abbreviation. You'll see it in documentation, other people's code, and interview questions. Use pd so readers don't have to stop and decode an unexpected name.

After this line, pd is the short name for the library you imported. The dot works the same way you've already seen: pd.DataFrame(...) means “take the DataFrame tool from pandas and run it.”

A table from a dictionary of lists

import pandas as pd

orders = pd.DataFrame({
    'order_id': [101, 102, 103, 104, 105, 106, 107, 108],
    'city':     ['Furrville', 'Catford', 'Furrville', 'Meowfield',
                 'Catford', 'Furrville', 'Tailford', 'Catford'],
    'price':    [10, 25, 8, 120, 17, 9, 50, 13],
    'qty':      [2, 1, 4, 1, 2, 6, 1, 2],
    'status':   ['paid', 'paid', 'cancelled', 'paid',
                 'paid', 'paid', 'cancelled', 'paid'],
})

Inside pd.DataFrame(...) is the same kind of dictionary you used in Chapter 2, only larger. Read it with one rule:

  • dictionary key → column name ('city');
  • list value → values in that column from top to bottom (['Furrville', 'Catford', ...]).

Every list must have the same length — here, each one contains eight values. Give pandas lists of different lengths and it will stop with ValueError: All arrays must be of the same length: a table with seven values in one column and eight in another isn't a valid table.

Here's the result. This eight-order archive will stay with you throughout the chapter, so get familiar with it. From here on, we'll change one small piece at a time:

indexorder_idcitypriceqtystatus
0101Furrville$102paid
1102Catford$251paid
2103Furrville$84cancelled
3104Meowfield$1201paid
4105Catford$172paid
5106Furrville$96paid
6107Tailford$501cancelled
7108Catford$132paid

Anatomy: five terms you need to keep straight

  • Column — a vertical slice: one characteristic across all orders. price contains the prices of all eight orders. A column has a name.
  • Row — a horizontal slice: one complete order. The row with index 0 means “order 101, Furrville, $10, quantity 2, paid.”
  • Cell — the intersection of a row and a column, containing one value: row with index 3, column city → 'Meowfield'.
  • Index — the row labels on the left (0, 1, 2, …, 7). The index is not a column: it won't appear in orders.columns, and you don't select it like a regular column with orders['index']. In this table, index labels work like row addresses.
  • Column name — the label at the top. Column names live in orders.columns.

Why does a table need an index if its labels initially match the row positions? A row can move while its label stays attached to it. Sort the table by price and the row for order 104 will move, but label 3 will move with it. That remains true until you explicitly reset or replace the index. In Lesson 2, we'll build a whole mechanism around this; in Lesson 5, the index will appear again after groupby.

DataFrame and Series

Pull out one column:

orders['city']

The result is a Series — one column with its own values, index, and name. A Series has three parts, and all three matter:

  1. values — Furrville, Catford, Furrville, …;
  2. index — the same 0–7 labels as the table;
  3. name — city.

This leads to the chapter's key definition: a DataFrame is several Series joined by a shared index. Think of it as a collection of columns aligned on the same set of row addresses. That shared index keeps the columns aligned, and the columns in one table all have the same length.

What we writeWhat we getExample
ordersDataFrame — the whole table8 rows × 5 columns
orders['city']Series — one column8 values + index + name city
orders['price'].sum()one number252

You'll need to distinguish DataFrames from Series often because some of their properties and methods differ. For example, a DataFrame has .columns, while a Series has .name. An AttributeError: ... object has no attribute ... therefore often means you expected a table but are working with a column, or vice versa.

order_idcitypriceqty0101Furrville1021102Catford2512103Furrville843104Meowfield1201DataFramethe whole tablecolumn namescolumnsindexrow labelsSeriesa singlecolumncell — one valuea DataFrame is a set of Series sharing one index
DataFrame anatomy: column names are at the top, the index is on the left, and a cell sits at the intersection of a row and a column. A single column is a Series: values, the same index, and a name.

First look: head(), tail(), sample()

The first thing an investigator does with an unfamiliar table is look at it. Not all of it: the real Kotomarket archive contains millions of rows, so printing the whole table would be pointless.

orders.head()     # first 5 rows (by default)
orders.head(3)    # first 3
orders.tail(2)    # last 2
orders.sample(3, random_state=7)   # 3 random rows

Why use three different ways to inspect a table?

  • head() — see what the columns and values look like and catch anything obviously strange;
  • tail() — check how the data ends. The last rows might reveal a “Total” row, an export that was cut off unexpectedly, or orders dated in the future;
  • sample() — inspect random rows from across the table instead of only the beginning or end. head() shows the oldest data only if the table is sorted by time. random_state=7 fixes the sample: with the same DataFrame, you and your coworker will see the same rows.

The table's profile: shape, columns, dtypes

orders.shape      # (8, 5) — 8 rows, 5 columns
orders.columns    # column names
orders.dtypes     # type of each column

shape is a pair of numbers in “rows, columns” order. For a DataFrame, the first number is the number of rows and the second is the number of columns. orders.shape[0] is the row count; orders.shape[1] is the column count.

Method or attribute: when do you use parentheses?

In Chapter 2, you already learned the difference between a “function,” a “method,” and an “attribute.” In pandas, the distinction becomes practical: the same object can have both methods and attributes, and mixing up the parentheses is one of the most common beginner mistakes.

We writeWhat it isParentheses
orders.shapeattribute — a ready-made propertyno
orders.columnsattributeno
orders.dtypesattributeno
orders.head()method — an actionyes
orders.sample(3)method with an argumentyes
orders['price'].sum()methodyes

The rule is simple: read an attribute without parentheses; call a method with parentheses. An attribute usually describes the object's current state, while a method performs an action and may accept settings. That's why you get the table dimensions from shape, while the instruction “show me the first three rows” goes to the method head(3).

What happens if you mix them up?

orders.head        # <bound method NDFrame.head of ...> — method description, not rows
orders.head()      # first 5 rows — what we want

orders.shape()     # TypeError: 'tuple' object is not callable

The second mistake is easier to spot because it fails immediately. The first is sneakier: the code doesn't crash, but instead of the table you see a technical-looking message and may wonder whether the library is broken. If you see <bound method ...> in the output, you forgot the parentheses. If you see object is not callable, you added parentheses where they don't belong.

Column types: what operations can you use?

A data type (dtype) tells you what pandas thinks each column contains. The type determines which operations are available.

dtypeWhat it storesWhat it allows
int64integers+ - * /, sum, mean, comparisons > <, numeric sorting
float64decimal numbersthe same, plus fractional values; can store missing value NaN
objectPython objects; often text, but may contain mixed typesfor text values — operations through .str, comparison ==, text sorting
string or strtextoperations through .str, comparison ==, text sorting
boolTrue / False&, |, ~; the sum() method counts True values
datetime64[ns]dates and timesoperations through .dt, date subtraction, chronological sorting

In our table, order_id, price, and qty are int64, while city and status contain text. pandas often uses the object type for text columns. Depending on the pandas version, settings, and how the column was created, you may also see a dedicated string or str type for text; in the course environment, our table shows str. For this table, the meaning is the same: these columns contain text, so you can't treat them as numbers.

That's why you check dtypes at the start of an investigation. If a “numeric” column actually contains text, sum() may join the values into one long string or fail with an error, but it won't calculate a numeric total. Sorting may then decide that '890' is greater than '10000' because it compares the strings character by character: '8' is greater than '1'. Chapter 4 is devoted to fixing columns like these. For now, remember the sequence: when you encounter an unfamiliar table, check shape, head(), and dtypes.

Calculate over a column

A Series has built-in methods for — reducing a set of values to one result. Python's built-in len() function, meanwhile, gives you the number of rows in a DataFrame:

orders['price'].sum()     # 252 — sum of all prices
orders['price'].mean()    # 31.5 — average price
orders['price'].max()     # 120 — highest-priced item
orders['price'].min()     # 8
len(orders)               # 8 — number of rows (same as shape[0])

The first four expressions aggregate the Series orders['price'], while len(orders) counts rows in the whole table. You don't need a loop or have to process all eight values yourself; pandas performs the calculation on the entire column at once. In Lesson 4, we'll look at how that works in detail.

L., log entry #3: The first thing I do with any new export is shape, head, dtypes. Thirty seconds. Once, in those thirty seconds, I found a table with 400,000 rows instead of the expected 40,000 — the export had been concatenated with itself ten times. The report based on it had already been sent upstairs.

The same eight-order archive is already stored in orders. Run the cell and compare the results: shape without parentheses returns a pair of numbers, head(3) with parentheses returns rows, and orders['city'] is a Series with its own index and name.
python · pandas
Practice: write the code
QUERY wants the archive's profile. Using the orders table, calculate:
  • n_rows — the number of rows,
  • n_cols — the number of columns,
  • col_names — a list of column names,
  • max_price — the largest value in the price column (as an integer).
A hint about parentheses: three of these values come from an attribute, and one comes from a method.
python · pandas
Practice: write the code
A second sheet turns up in the black box: the returns log. Build a DataFrame called returns yourself from a dictionary of lists: an order_id column with the values 103, 107, 105 and a reason column with the values 'damaged packaging', 'wrong size', 'changed mind'. Then store the number of rows in the resulting table in returns_rows.
python · pandas
Check yourself
An analyst wrote orders.shape() — with parentheses. What happens?
Check yourself
How is orders['price'] different from orders?
Key takeaways
  • import pandas as pd — import the library and refer to it as pd; pd.DataFrame(...) creates a DataFrame from the data you pass in
  • you can build a DataFrame from a dictionary of lists: key → column name, list → values; all lists must have the same length
  • anatomy: row, column, cell, index (row addresses, not a column), column name
  • DataFrame = several Series sharing one index; Series = values + index + name
  • inspect data with head(), tail(), sample(n, random_state=7)
  • basic profile: shape (rows, columns), columns, dtypes — all three are attributes, so no parentheses
  • read an attribute; call a method with parentheses; <bound method ...> in the output = you forgot the parentheses
  • a column's type determines which operations are available: numeric calculations require a numeric type, while text uses string operations

Next: how to pull exactly what you need from a table — one column, several columns, or a specific row.