DataFrame

Build tables from dicts, lists, and Series. Read shape, columns, and the index.

A DataFrame is a table: named columns, one row per record, a shared index. It is the object you will use for almost every exercise after this page.

Goal

Construct DataFrames several ways and read .shape, .columns, and .index before you compute.

From a dict of lists

Each key becomes a column. Lists must be the same length.

df = pd.DataFrame(
    {
        "name": ["Ada", "Alan", "Grace", "Linus"],
        "score": [98, 91, 95, 88],
        "team": ["A", "B", "A", "B"],
    }
)
print(df)
print()
print("shape:", df.shape)
print("columns:", list(df.columns))
print("index:", list(df.index))
print("rows:", len(df))

shape is (rows, columns) — here (4, 3).

From a list of dicts

Useful when each record arrives as a mapping (JSON APIs look like this).

rows = [
    {"city": "Nairobi", "product": "A", "units": 12},
    {"city": "Mombasa", "product": "B", "units": 7},
    {"city": "Kisumu", "product": "A"},
]
df = pd.DataFrame(rows)
print(df)

Kisumu has no units, so that cell is NaN.

From Series

prices = pd.Series({"A": 10.5, "B": 22.0}, name="price")
units = pd.Series({"A": 12, "B": 7, "C": 2}, name="units")
df = pd.DataFrame({"price": prices, "units": units})
print(df)

Indexes union. Product C has units but no price.

Set a useful index

df = pd.DataFrame(
    {
        "name": ["Ada", "Alan", "Grace"],
        "score": [98, 91, 95],
    }
)
named = df.set_index("name")
print(named)
print()
print(named.loc["Ada"])
print()
print(named.reset_index())

set_index does not change df unless you assign the result (or pass inplace=True — prefer assignment).

Empty frame with columns

empty = pd.DataFrame(columns=["city", "product", "units"])
print(empty)
print(empty.shape)
Pitfall

df.columns is an Index, not a Python list. Use list(df.columns) when you want to print or mutate a plain list.