Lesson 16 of 23
❮Prev Next❯

PY-401 · Summarising and joining

Pivot tables

⏱ 8 min 🐍 Real Python 3 🎬 Animated

16of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    ⚡ 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.

    Pivot tables, running
    1. import pandas as pd
    2. sales = pd.DataFrame({
    3. "month": ["Jan", "Jan", "Feb", "Feb", "Feb", "Mar"],
    4. "region": ["North", "South", "North", "South", "North", "South"],
    5. "revenue": [120, 90, 200, 150, 80, 60],
    6. })
    7. table = sales.pivot_table(index="region", columns="month", values="revenue",
    8. aggfunc="sum", fill_value=0)
    9. print(table[["Jan", "Feb", "Mar"]])
    10. print(pd.crosstab(sales["region"], sales["month"])[["Jan", "Feb", "Mar"]])
    Press ▶ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideadf.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.
    3. 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"])

    ▶ Run the example 🎬 Watch it come alive

    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.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. In pivot_table, what does index= choose?
    2. 2. Which argument shows 0 instead of NaN?
    3. 3. What does margins=True add?
    4. 4. pd.crosstab(a, b) by default shows…
    5. 5. A pivot table is like groupby by…

    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