Data Analysis · pandas Core · lesson 5 of 12
Series and DataFrames
about 15 minutes · free · runs in your browser
Step 1 of 2
Labels on top of arrays
pandas adds two things to NumPy: labels and mixed types per column.
A Series is a one-dimensional array with an index:
import pandas as pd
s = pd.Series([10, 20, 30], index=["a", "b", "c"])
s["b"] # 20
s.mean() # 20.0
A DataFrame is a table — a dictionary of Series sharing one index:
df = pd.DataFrame({
"city": ["London", "Lisbon", "Oslo"],
"temp": [14, 24, 3],
})
df["temp"] # a Series
df.shape # (3, 2) — rows, columns
df.columns # Index(['city', 'temp'])
df.head(2) # the first two rows
df.info() and df.describe() are the two things to run on any table you have not
seen before.
Your turn: build the DataFrame, then record its shape, its column names, and the mean temperature.
You start from this, and edit it in the browser:
import pandas as pd
cities = ["London", "Lisbon", "Oslo", "Tokyo"]
temps = [14, 24, 3, 19]
# Build df with columns "city" and "temp", then set shape, columns, mean_temp.
Step 2 of 2
Adding and deriving columns
A new column is just an assignment, and it can be computed from the others — vectorised, exactly like NumPy:
df["temp_f"] = df["temp"] * 9 / 5 + 32
df["is_warm"] = df["temp"] > 20
To drop one, df.drop(columns=["temp_f"]) returns a new table without it.
Your turn: add a temp_f column and a band column that reads "warm" when
the temperature is above 20 and "cool" otherwise.
You start from this, and edit it in the browser:
import pandas as pd
import numpy as np
df = pd.DataFrame({
"city": ["London", "Lisbon", "Oslo", "Tokyo"],
"temp": [14, 24, 3, 19],
})
# Add temp_f and band.