0Pricing
Learn AI with Python · Lesson

Pivot Tables and Cross-Tabulation

pd.pivot_table(), pd.crosstab(), reshaping data for summary statistics.

Pivot Tables and Cross-Tabulation is a free Learn AI with Python lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn AI with Python learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Reshaping for Insight

A pivot table reshapes long data into a grid, summarizing one value across two categorical axes. It is the spreadsheet pivot you know, but programmable.

import pandas as pd
df = pd.DataFrame({
    "region": ["E", "E", "W", "W", "E"],
    "product": ["A", "B", "A", "B", "A"],
    "sales": [10, 20, 30, 40, 50],
})

Basic pivot_table

pd.pivot_table takes values (the numbers to summarize), index (rows), and columns (columns). By default it averages duplicate cells.

pt = pd.pivot_table(df, values="sales", index="region", columns="product")
print(pt)
# product     A     B
# region
# E        30.0  20.0
# W        30.0  40.0

Choosing aggfunc

Set aggfunc to control how duplicates collapse: sum, mean, count, and more. Use a list for several at once.

pt = pd.pivot_table(df, values="sales", index="region",
                    columns="product", aggfunc="sum")
print(pt)

Multiple aggfuncs

Pass a list of functions to compute several summaries side by side.

pt = pd.pivot_table(df, values="sales", index="region",
                    aggfunc=["sum", "mean", "count"])
print(pt)

Filling Missing Cells

Combinations with no data become NaN. fill_value replaces them, often with 0, for clean reports.

pt = pd.pivot_table(df, values="sales", index="region",
                    columns="product", aggfunc="sum", fill_value=0)
print(pt)

Margins (Totals)

Set margins=True to append row and column grand totals, labeled "All" by default.

pt = pd.pivot_table(df, values="sales", index="region",
                    columns="product", aggfunc="sum",
                    fill_value=0, margins=True)
print(pt)

Multiple Index Levels

Pass lists to index or columns for hierarchical breakdowns, for example region then product.

df["channel"] = ["on", "off", "on", "off", "on"]
pt = pd.pivot_table(df, values="sales",
                    index=["region", "channel"], aggfunc="sum")
print(pt)

Cross-Tabulation with crosstab

pd.crosstab is a specialized pivot that COUNTS the frequency of combinations of two categoricals, no value column needed.

ct = pd.crosstab(df["region"], df["product"])
print(ct)
# product   A  B
# region
# E         2  1
# W         1  1

Normalizing crosstab

The normalize argument turns counts into proportions: "index" per row, "columns" per column, or True over the grand total.

ct = pd.crosstab(df["region"], df["product"], normalize="index")
print(ct)   # each row sums to 1.0

crosstab with Values

Provide values and aggfunc to make crosstab summarize a metric instead of counting, blurring the line with pivot_table.

ct = pd.crosstab(df["region"], df["product"],
                 values=df["sales"], aggfunc="sum")
print(ct)

pivot_table vs crosstab

Use pivot_table when summarizing a numeric value; use crosstab when counting frequencies of category combinations. crosstab also makes normalization to proportions a one-liner.

Quick Check

Test your reshaping knowledge.

Recap

Reshaping toolkit:

  • pd.pivot_table(values, index, columns, aggfunc) summarizes a metric
  • fill_value for empty cells, margins=True for totals
  • List index/columns for hierarchy
  • pd.crosstab counts combinations; normalize yields proportions

Frequently asked questions

Is the “Pivot Tables and Cross-Tabulation” lesson free?

Yes — the full text of “Pivot Tables and Cross-Tabulation” is free to read here on the web, and the Learn AI with Python course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.

What will I learn in “Pivot Tables and Cross-Tabulation”?

pd.pivot_table(), pd.crosstab(), reshaping data for summary statistics. You practise Learn AI with Python with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn AI with Python?

No prior experience is required. Learn AI with Python on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Pivot Tables and Cross-Tabulation” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn AI with Python lesson?

Yes. Every Learn AI with Python lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. GroupBy and Aggregation
  2. Pivot Tables and Cross-Tabulation
  3. Advanced Merging and Joining
  4. Time Series in Pandas
← Back to Learn AI with Python