pivot_table()
pivot_table builds a spreadsheet-style summary table with one variable down the side and another across the top.
In this page:
Syntax
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()
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
- Forgetting the default aggfunc is mean
- Passing duplicates to pivot instead
- 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: