← Back to Pandas Course | Chapter 7: Grouping & Aggregation | Lesson 5 of 7

pivot_table()

pivot_table builds a spreadsheet-style summary table with one variable down the side and another across the top.

In this page:

  1. pivot_table()
Syntax
python
pd.pivot_table(df, values="value_column", index="row_column", columns="column_column", aggfunc="function_name")

pivot_table()

pivot_table(values, index, columns, aggfunc) groups by index and columns and aggregates the values. The default aggregation is mean. Use margins=True to add totals and fill_value to replace NaN.

Note: pivot_table handles duplicate entries by aggregating, unlike pivot which raises an error.

Example: pivot_table()

python
import pandas as pd

df = pd.DataFrame({
    "region": ["N", "N", "S", "S", "S"],
    "product": ["a", "b", "a", "a", "b"],
    "sales": [10, 20, 30, 40, 50],
})
print(df.pivot_table(values="sales", index="region", columns="product", aggfunc="sum", fill_value=0, margins=True))

# Output:
# product   a   b  All
# region
# N        10  20   30
# S        70  50  120
# All      80  70  150
Related Topics
Common Mistakes
  1. Forgetting the default aggfunc is mean
  2. Passing duplicates to pivot instead
  3. Not filling empty combinations
Chapter Summary
  • pivot_table summarizes across two keys
  • Default aggfunc is mean
  • margins adds totals
  • fill_value replaces NaN
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.