Module 5 · Pandas: Your Data Workbench · Lesson 18 of 51

Combine, reshape and report

merge and concat, melt and pivot between wide and long, apply and method chaining, then a full monthly report project.

In this lesson · about 50 minutes

  • Join DataFrames with merge and stack them with concat
  • Reshape between wide and long with melt and pivot
  • Write a clean, chained analysis and turn it into a report

merge and concat

orders.merge(targets, on="branch", how="left")         # how = inner, left, right, outer
pd.concat([jan, feb, mar], ignore_index=True)            # stack rows

Add validate="many_to_one" to merge and pandas will stop you if the right table unexpectedly has duplicate keys: the fan-out trap from Module 3, caught automatically. indicator=True adds a column saying whether each row matched.

Wide and long

wide = long.pivot(index="branch", columns="month", values="revenue")
long = wide.reset_index().melt(id_vars="branch", var_name="month", value_name="revenue")

Charts and BI tools prefer long; humans often read wide more easily.

apply and map

s.map({"Card": "Digital", "App": "Digital", "Cash": "Cash"}) relabels values. s.apply(my_function) runs your function on every value. Prefer built-in vectorised methods when they exist: they're much faster.

Method chaining

report = (orders
          .query("branch != 'Airport'")
          .assign(month=lambda d: d["date"].dt.to_period("M"))
          .groupby(["month", "branch"], as_index=False)["total"].sum()
          .sort_values(["month", "total"], ascending=[True, False]))

Each line is one step, read top to bottom. assign adds columns inside a chain.

Targets vs actuals, and a wide-to-long round trip

Exercise

Attach targets and find the gap

Merge branch_rev (total revenue per branch) with targets on branch (a left merge), add a column gap = revenue - target, and keep the result in result, sorted by gap ascending (worst first).

Code that runs before yours
import pandas as pd
orders = pd.read_csv("kc_orders.csv", parse_dates=["date"])
branch_rev = orders.groupby("branch", as_index=False).agg(revenue=("total", "sum"))
targets = pd.DataFrame({"branch": ["Downtown", "Riverside", "Campus", "Airport"], "target": [10000, 6000, 7500, 6000]})

Exercise

Wide to long

wide has one column per quarter. Turn it into long with columns branch, quarter and sales using melt. Then set best_q to the quarter with the highest total sales across branches.

Exercise

Project: the monthly report

Write one chain that builds report: for each month (orders["date"].dt.to_period("M") as a column named month), the number of orders n_orders, revenue revenue (rounded to 2) and average order avg_order (rounded to 2), plus growth: revenue's percent change from the previous month (use .pct_change(), rounded to 3). Months in order, with month as the index.

Code that runs before yours
import pandas as pd
orders = pd.read_csv("kc_orders.csv", parse_dates=["date"])

Flashcards

Module 5 flashcards

0 of 10 known

Say the answer out loud, flip the card, then be honest: cards you miss come back at the end.

10 left in the deck

Practice exam

Module 5 checkpoint

10 questions, 12 minutes.

  • 10 questions · 12 minutes
  • No feedback until you submit. Flag questions to come back to them.
  • Aim for 85% or better before you move on. The real exam's 750 out of 900 is roughly 80–83%.

Exercises solved: 0 of 3

Tip: solve each exercise first. Press Check to test your code.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.