pandas · Lesson 1.2

Building DataFrames

Make a DataFrame from a dictionary or a list of records, and add columns to it.

1From a dictionary of columns

A dictionary whose values are lists becomes a DataFrame: each key is a column name and each list is that column.

import pandas as pd

df = pd.DataFrame({
    "city": ["Lisbon", "Osaka", "Lima"],
    "population_m": [0.55, 2.75, 10.0],
})
df
pandas

Practice

Build a DataFrame with columns product (tea, mug, cake) and price (3.5, 9.0, 4.25) and store it in result.

import pandas as pd

result = ...
pandas

2From a list of records

A list of dictionaries, one per row, also becomes a DataFrame. That's the shape most API and JSON data arrives in.

import pandas as pd

rows = [
    {"id": 1, "name": "Ana", "plan": "pro"},
    {"id": 2, "name": "Ben", "plan": "basic"},
]
pd.DataFrame(rows)
pandas

Practice

Turn events into a DataFrame and store it in result.

import pandas as pd

events = [
    {"user": "u1", "event": "view", "ms": 120},
    {"user": "u2", "event": "click", "ms": 45},
    {"user": "u1", "event": "buy", "ms": 300},
]
result = ...
pandas

3Add a column

Assigning to a new column name adds it. The new column is usually worked out from existing ones.

import pandas as pd

df = pd.DataFrame({"price": [3.5, 9.0, 4.25], "qty": [10, 3, 8]})
df["revenue"] = df["price"] * df["qty"]
df
pandas

Practice

Add a column price_eur that is price_usd * 0.92, rounded to 2 decimals, then store the whole DataFrame in result.

import pandas as pd

df = pd.DataFrame({"item": ["tea", "mug"], "price_usd": [3.5, 9.0]})
# add price_eur
result = df
pandas

4A column with one value

Assigning a single value fills the whole column with it, handy for labels like a source or a date.

import pandas as pd

df = pd.DataFrame({"order_id": [101, 102, 103]})
df["source"] = "web"
df
pandas

Practice

Add a column region with the value "EU" for every row, and store the DataFrame in result.

import pandas as pd

df = pd.DataFrame({"store": ["Lisbon", "Madrid", "Paris"], "sales": [120, 340, 210]})
# add region
result = df
pandas