PY-401 · Summarising and joining
Pivot tables
⏱ 8 min 🐍 Real Python 3 🎬 Animated ✓ Completed
⚡ The 30-second answer
A pivot table turns long data into a grid: one row per value of one column, one column per value of another, and a summary in each cell. df.pivot_table(index="region", columns="month", values="revenue", aggfunc="sum") gives revenue per region per month. pd.crosstab(a, b) is the shortcut for counting how often each pair appears.
- Build a pivot table with pivot_table
- Fill empty cells with fill_value
- Count pairs with crosstab
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import pandas as pdsales = pd.DataFrame({"month": ["Jan", "Jan", "Feb", "Feb", "Feb", "Mar"],"region": ["North", "South", "North", "South", "North", "South"],"revenue": [120, 90, 200, 150, 80, 60],})table = sales.pivot_table(index="region", columns="month", values="revenue",aggfunc="sum", fill_value=0)print(table[["Jan", "Feb", "Mar"]])print(pd.crosstab(sales["region"], sales["month"])[["Jan", "Feb", "Mar"]])
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
month Jan Feb Mar
region
North 120 280 0
South 90 150 60
month Jan Feb Mar
region
North 1 2 0
South 1 1 1 🎯 Set grid to a pivot table of visits with "page" as rows, "day" as columns and the sum of "views" in each cell, with 0 for empty cells.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
grid = visits.pivot_table(index="page", columns="day", values="views", aggfunc="sum", fill_value=0)
- The problemYour manager loves the Excel pivot table on the monthly report. Rebuilding it by hand each month takes an hour. pandas builds the same grid in one call.
- The Python idea
df.pivot_table(index="rows", columns="cols", values="num",A pivot table turns long data into a grid: one row per value of one column, one column per value of another, and a summary in each cell. - In real lifeA school builds
marks.pivot_table(index="student", columns="subject", values="score")so each teacher sees the whole class on one screen, one student per row.
Start with a question
Your manager loves the Excel pivot table on the monthly report. Rebuilding it by hand each month takes an hour. pandas builds the same grid in one call.
Grids are how people read summaries: in reports, slides and dashboards. pivot_table is groupby by two keys, laid out the way managers expect.
Explain it like I'm 10
Imagine a sticker chart with friends down the side and days across the top. Each square shows how many stickers that friend got that day. That grid is a pivot table.
The technical explanation
index picks the rows, columns picks the columns, values is the number to summarise and aggfunc is how (sum, mean, count).
Combinations with no data are NaN. fill_value=0 shows 0 instead.
margins=True adds an "All" row and column with the totals.
pd.crosstab(df["region"], df["month"]) counts how many rows have each pair, which is handy for "how many orders" questions.
Syntax
df.pivot_table(index="rows", columns="cols", values="num",
aggfunc="sum", fill_value=0)
pd.crosstab(df["a"], df["b"]) Real-world scenario
A school builds marks.pivot_table(index="student", columns="subject", values="score") so each teacher sees the whole class on one screen, one student per row.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
🏆 Every lesson counts toward your certificate Next: merge and join →Questions people ask
What is the difference between pivot and pivot_table in pandas?
pivot only reshapes and fails if a row and column pair appears twice. pivot_table also summarises duplicates with aggfunc, so it works on raw transaction data.
How do I flatten a pandas pivot table?
Call .reset_index() to turn the row labels into a column. If the columns have several levels, join them with table.columns = ["_".join(map(str, c)) for c in table.columns].
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between pivot and pivot_table in pandas?
pivot only reshapes and fails if a row and column pair appears twice. pivot_table also summarises duplicates with aggfunc, so it works on raw transaction data.
beginner How do I flatten a pandas pivot table?
Call .reset_index() to turn the row labels into a column. If the columns have several levels, join them with table.columns = ["_".join(map(str, c)) for c in table.columns].
intermediate In pivot_table, what does index= choose?
The rows. index sets the row labels.
intermediate Which argument shows 0 instead of NaN?
fill_value=0. fill_value replaces empty cells.
Quick revision
Remember
- Build a pivot table with pivot_table
- Fill empty cells with fill_value
- Count pairs with crosstab
- Months sort alphabetically (Feb before Jan). Pick the order you want with
table[["Jan", "Feb", "Mar"]], or convert months to real dates first.
Syntax
df.pivot_table(index="rows", columns="cols", values="num",
aggfunc="sum", fill_value=0)
pd.crosstab(df["a"], df["b"]) Official documentation
- Reshaping and pivot tables (docs.python.org)