Lesson 4 · Exercises

Practise on your own

Exercise 1 · Create your own data

Build a table of five products and compute the total value. Then change the prices and run it again.

import pandas as pd

products = ["Laptop", "Mouse", "Keyboard", "Monitor", "Headphones"]
prices = [1200, 25, 75, 350, 120]

product_df = pd.DataFrame({"Product": products, "Price": prices})
total = product_df["Price"].sum()
print(f"Total inventory value: ${total:,}")
Total inventory value: $1,770

Exercise 2 · Load a real dataset

This exercise downloads the public Titanic dataset, so it needs an internet connection. It was not run when this page was built: run it on your computer.

url = "https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv"
titanic = pd.read_csv(url)

print(f"Dataset shape: {titanic.shape}")
print(f"Columns: {list(titanic.columns)}")
print(titanic.head(3))

Exercise 3 · Answer three questions

Using the titanic table from exercise 2:

  1. How many passengers survived?
  2. What was the average age?
  3. What was the average fare in each class?
survived = titanic["Survived"].sum()
print(f"Survivors: {int(survived)}")

avg_age = titanic["Age"].mean()
print(f"Average age: {avg_age:.1f}")

print(titanic.groupby("Pclass")["Fare"].mean().round(2))
Tip

Try to write your own answer before reading the code above.