← Learning Hub
Advanced

Pivot Tables and Crosstabs

A pivot table puts one thing down the side, another across the top, and a total in each box - just like Excel.

Pivot tables summarise data in two directions at once - cities down the side, months across the top. They're the quickest way to spot patterns, and melt reshapes data the other way when a tool needs long format.

Example
You can edit this code.

crosstab: counting combinations

Example
You can edit this code.

Reshaping: melt

melt does the opposite of a pivot: wide table to long table. Many charting tools want long tables.

Example
You can edit this code.
Key points
  • pivot_table summarises by rows and columns.
  • crosstab counts combinations.
  • melt turns wide tables into long ones.

📝 Test yourself

1. In pivot_table, what goes in 'columns'?
2. What does crosstab do by default?
3. Fill in the option that adds a Total row and column:
df.pivot_table(..., =True)