← Data analysis with Python

DataFrames: whole tables

Build a table from a dictionary or read it from CSV text.

Start this lesson

A DataFrame is a whole table: several Series side by side, sharing one index. You can build one from a dictionary of lists (each key becomes a column), or read CSV text with pd.read_csv. read_csv is smarter than the csv module: it uses the header for column names and turns number columns into numbers automatically. Each column you take out of a DataFrame is a Series, so everything you learned about Series still works.

import io
import pandas as pd

pets = pd.DataFrame({
    "name": ["Biscuit", "Luna", "Mango"],
    "kind": ["dog", "cat", "parrot"],
    "age": [4, 7, 2],
})
print(pets)

text = """city,temp
Oslo,4
Cairo,31
"""
weather = pd.read_csv(io.StringIO(text))
print(weather["temp"].mean())

The dictionary keys became columns. read_csv read the CSV text and already treated temp as numbers, so .mean() works right away (17.5).

In real work you write pd.read_csv("file.csv"). Here we pass io.StringIO(text) so the data lives inside the program.