0PricingLogin
Learn AI with Python · Lesson

Pivot Tables and Cross-Tabulation

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

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

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