Chapter 9 · 9 levels

Reshaping data

Turn long tables into wide grids and back with pivot_table, melt, stack, unstack and crosstab, on real Harbor & Pine orders, returns and sessions.

Start

A groupby gives you one row per combination: channel and status, category and year, device and source. That long shape is perfect for computing, but nobody reads a 21-row list of combinations in a meeting. Colleagues want a grid: channels down the side, statuses across the top, one number in each cell. And the opposite happens just as often: Marketing hands you a spreadsheet with a column per channel, and you need it long again before you can group, merge or chart it.

This chapter is about moving between those two shapes on purpose. You’ll build grids with pivot_table, fill the empty cells honestly, turn a wide sheet back into a long table with melt, use unstack and stack to swap an index level into the columns and back, and build share tables with crosstab. The boss level builds a finance-ready revenue report by channel and year, adds a growth column, and turns it back into the long shape a chart or a database expects.

Levels

  1. Orders by channel and status, as a grid

    from Megan Collins, Head of Sales

    pivot table, aggfunc, fill value, wide format

    Code Difficulty 2 of 5 Not started

  2. Revenue per category, several ways

    from Thomas Whitaker, Head of Merchandising

    pivot table, aggfunc list, multiindex columns, merge, dt year

    Code Difficulty 3 of 5 Not started

  3. Turn the budget sheet into a long table

    from Jordan Reyes, Head of Marketing

    melt, long format, id vars, var name, value name

    Code Difficulty 2 of 5 Not started

  4. Wide or long?

    from Priya Shah, Head of Data

    long format, wide format, tidy data

    Quiz Difficulty 2 of 5 Not started

  5. Coupon orders by status

    from Andrew Ramos, Marketing Manager

    unstack, stack, multiindex, fill value, groupby multiple keys

    Code Difficulty 3 of 5 Not started

  6. Why each category gets returned

    from Angela Rivera, Head of Customer Support

    crosstab, normalize, shares, merge

    Code Difficulty 3 of 5 Not started

  7. Conversion rate by device and source

    from Jordan Reyes, Head of Marketing

    pivot table, mean of boolean, margins, pivot vs pivot table

    Code Difficulty 4 of 5 Not started

  8. Units sold per product tag

    from Thomas Whitaker, Head of Merchandising

    explode, ast literal eval, list column, apply, merge, groupby

    Code Difficulty 4 of 5 Not started

  9. Boss: the channel report for the board

    from Laura Bennett, Head of Finance

    pivot table, growth rate, month name, reindex, idxmax, sum axis

    Boss · 4 steps Difficulty 4 of 5 Not started

Pick what may run on this site. You can change this any time from "Cookie settings" at the bottom of every page.