Module 4 of 6 · 50 minutes

Working with data in pandas

pandas turns Python into a powerful, repeatable spreadsheet. It's the tool you'll use to prepare data for — and analyse results from — AI.

By · Last updated

Learning objectives

  • Create and inspect DataFrames
  • Select columns and filter rows
  • Handle missing values and add columns
  • Group and summarise data
  • Plot and save results
  • Convert text to dates and group by month
  • Join two tables and check the result

4.1 What pandas is for

pandas is the standard Python library for working with tables of data — like a programmable spreadsheet. Its main object is the DataFrame: rows and named columns. (The first run on this page takes a little longer while pandas loads.)

import pandas as pd

df = pd.DataFrame({
    "order_id": ["A1", "A2", "A3", "A4", "A5", "A6"],
    "product":  ["board", "oil", "board", "utensils", "board", "oil"],
    "region":   ["UK", "UK", "IE", "UK", "IE", None],
    "qty":      [2, 1, 1, 3, None, 2],
    "price":    [24.99, 6.50, 24.99, 12.00, 24.99, 6.50],
})
print(df.head())        # first rows
df.info()                 # columns, types and missing values
print(df.describe())      # summary statistics for numeric columns

To load real data: pd.read_csv("file.csv") or pd.read_excel("file.xlsx").

order_idproductregionqtyprice0A1boardUK224.991A2oilUK16.502A3boardIE124.993A4utensilsUK312.00columns (named)indexdf["qty"] — one column (a Series)
Anatomy of a DataFrame: an index labels the rows, named columns hold one kind of value each.

4.2 Selecting and filtering

print(df["product"])                         # one column
print(df[["product", "price"]])              # several columns
print(df[df["region"] == "UK"])              # rows where region is UK
print(df[(df["product"] == "board") & (df["price"] > 20)])   # combine with & (and), | (or)

4.3 New columns and missing values

print(df.isna().sum())                # count missing values per column
df["qty"] = df["qty"].fillna(1)       # a business decision: assume 1 if missing
df["region"] = df["region"].fillna("Unknown")
df["revenue"] = df["qty"] * df["price"]
print(df)
Missing values are decisions

Filling, dropping or leaving gaps changes your results. Write down what you chose and why — the Data Quality course goes deeper.

4.4 Grouping and summarising

by_product = df.groupby("product")["revenue"].sum().sort_values(ascending=False)
print(by_product)

summary = df.groupby("region").agg(orders=("order_id", "count"),
                                   revenue=("revenue", "sum"))
print(summary)
SplitApply: sum()Combineboard49.98board24.99board24.9999.96oil6.50oil13.0019.50utensils36.0036.00board99.96oil19.50utensils36.00
df.groupby("product")["revenue"].sum(): split rows into groups, apply a calculation to each, combine the results.

4.5 A quick chart

import matplotlib.pyplot as plt

by_product.plot(kind="bar", title="Revenue by product")
plt.ylabel("£")
plt.tight_layout()
plt.show()

4.6 Saving results

df.to_csv("orders_clean.csv", index=False)
print(pd.read_csv("orders_clean.csv").head(3))    # read it back to check

# On your own computer you can also save to Excel:
# summary.to_excel("summary.xlsx")      # may need: pip install openpyxl

4.7 Working with dates

Most business questions have "per month" or "since when" in them. pandas turns text into real dates, and real dates can be compared, subtracted and grouped.

sales = pd.DataFrame({
    "order_id": ["B1", "B2", "B3", "B4", "B5", "B6", "B7"],
    "date": ["2026-09-03", "2026-09-17", "2026-10-02", "2026-10-21", "2026-10-29", "2026-11-05", "2026-11-18"],
    "product": ["board", "oil", "board", "utensils", "oil", "board", "utensils"],
    "amount": [49.98, 6.50, 24.99, 36.00, 13.00, 74.97, 12.00],
})
sales["date"] = pd.to_datetime(sales["date"])          # text -> real dates
sales.info()

sales["month"] = sales["date"].dt.to_period("M")        # 2026-09, 2026-10, ...
print(sales.groupby("month")["amount"].agg(["count", "sum"]))

print("Days between first and last order:", (sales["date"].max() - sales["date"].min()).days)
print(sales[sales["date"] >= "2026-11-01"])             # filter by date

Until a column has been through pd.to_datetime it is just text, and text sorts alphabetically: "10/01/2026" comes before "9/01/2026". Converting first is what makes sorting, filtering and grouping by date behave.

4.8 Joining two tables

Data rarely lives in one table. Orders are in one place and product details in another, linked by a shared column. merge brings them together, like VLOOKUP in a spreadsheet but for the whole table at once.

products = pd.DataFrame({
    "product": ["board", "oil", "apron"],
    "category": ["kitchenware", "care", "textiles"],
    "cost": [11.00, 2.10, 7.50],
})

joined = sales.merge(products, on="product", how="left")
print(joined[["order_id", "product", "amount", "category", "cost"]])
print("Rows with no matching product:", joined["category"].isna().sum())

how="left" keeps every order, even when the product table has no match — which is why the utensils rows show NaN. The default, how="inner", would have silently dropped them. Count the rows before and after any join: an unexpected change means missing or duplicated keys, and it is the most common source of wrong totals in data work.

4.9 Reading a chain of steps

pandas code is often written as one chain, each step feeding the next. Read it top to bottom as a recipe:

result = (
    joined
    .dropna(subset=["category"])                         # keep orders we can categorise
    .assign(profit=lambda d: d["amount"] - d["cost"])    # add a column
    .groupby("category")["profit"]                       # one group per category
    .sum()                                               # total profit in each
    .sort_values(ascending=False)                        # biggest first
    .round(2)
)
print(result)

If a chain gives a surprising answer, debug it the way you would a recipe: comment out the later steps and print the result after each one.

Exercise: best-selling region

Using the DataFrame above (after filling missing values and adding revenue), find the region with the highest total revenue and the average order quantity per product.

Your turn# Write your code here, then press Run
Show a solution
best_region = df.groupby("region")["revenue"].sum().idxmax()
avg_qty = df.groupby("product")["qty"].mean().round(2)
print(best_region)
print(avg_qty)
Exercise: monthly sales by product

From the orders_log table in the starter code, build a table with one row per month and one column per product, showing total amount (hint: pivot_table with aggfunc="sum", or groupby on two columns then unstack). Which product had the best single month?

Your turnimport pandas as pd

orders_log = pd.DataFrame({
    "date": ["2026-09-03", "2026-09-17", "2026-10-02", "2026-10-21", "2026-10-29", "2026-11-05", "2026-11-18"],
    "product": ["board", "oil", "board", "utensils", "oil", "board", "utensils"],
    "amount": [49.98, 6.50, 24.99, 36.00, 13.00, 74.97, 12.00],
})

# Convert the dates, add a month column, build the table, then press Run
Show a solution
import pandas as pd

orders_log = pd.DataFrame({
    "date": ["2026-09-03", "2026-09-17", "2026-10-02", "2026-10-21", "2026-10-29", "2026-11-05", "2026-11-18"],
    "product": ["board", "oil", "board", "utensils", "oil", "board", "utensils"],
    "amount": [49.98, 6.50, 24.99, 36.00, 13.00, 74.97, 12.00],
})

orders_log["date"] = pd.to_datetime(orders_log["date"])
orders_log["month"] = orders_log["date"].dt.to_period("M")

table = orders_log.pivot_table(index="month", columns="product", values="amount", aggfunc="sum", fill_value=0)
print(table)
print("Best single month:", table.stack().idxmax(), table.stack().max())

Key takeaways

  • A DataFrame is a table with named columns.
  • head(), info() and describe() give a quick overview.
  • Filter with conditions combined by & and |.
  • Treat missing-value handling as a documented decision.
  • groupby + agg answers most summary questions.
  • Convert dates with pd.to_datetime before sorting, filtering or grouping by them.
  • Count rows before and after a merge; a left join keeps unmatched rows visible.