🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpandas

pandas Documentation

LOADING ENGINE...

pd.pivot_table()

AI & DATA SCIENCE // pd-pivot-table

pd.pivot_table() reshapes data into a wide format like df.pivot(), but explicitly aggregates values when the same index/columns combination appears more than once.

Syntax

pd.pivot_table(data, index=None, columns=None, values=None, aggfunc='mean')

Deep Dive Course

pivot_table() accepts the same index/columns/values structure as pivot(), but adds an aggfunc parameter, mean by default, that combines multiple values sharing the same position into a single summary number instead of requiring uniqueness. This makes it strictly more flexible than pivot() for real-world, non-unique data, and it's essentially the pandas equivalent of a spreadsheet pivot table, letting you cross-tabulate and summarize data by two categorical dimensions at once.

1Understanding pd.pivot_table()

pivot_table() accepts the same index/columns/values structure as pivot(), but adds an aggfunc parameter, mean by default, that combines multiple values sharing the same position into a single summary number instead of requiring uniqueness. This makes it strictly more flexible than pivot() for real-world, non-unique data, and it's essentially the pandas equivalent of a spreadsheet pivot table, letting you cross-tabulate and summarize data by two categorical dimensions at once.

💡

Reach for pivot_table() over plain pivot() whenever duplicate index/columns combinations are even a remote possibility — pivot_table() simply averages, or otherwise aggregates, duplicates together instead of raising an error, which makes it the safer default for real-world, messier data.

editor.html
import pandas as pd

df = pd.DataFrame({"date": ["d1", "d1", "d1"], "city": ["NYC", "NYC", "LA"], "temp": [30, 32, 60]})
print(pd.pivot_table(df, index="date", columns="city", values="temp", aggfunc="mean"))
localhost:3000

2Practical Example

Here is a real-world application of pd.pivot_table() showing how it is used in production Pandas code.

editor.html
import pandas as pd

df = pd.DataFrame({"region": ["East", "East", "West"], "product": ["A", "A", "A"], "sales": [100, 150, 200]})
print(pd.pivot_table(df, index="region", columns="product", values="sales", aggfunc="sum"))
localhost:3000

3Best Practices

Follow these guidelines when working with pd.pivot_table():

1. Use pivot_table() by default over pivot() for real-world data, since it gracefully aggregates duplicates instead of requiring strict uniqueness

2. Choose aggfunc deliberately, sum, count, mean, etc., based on what the summarized value should actually represent, rather than relying on the mean default

3. Pass margins=True when you also want row/column subtotals included automatically, instead of computing them separately

⚠️

Tip: Reach for pivot_table() over plain pivot() whenever duplicate index/columns combinations are even a remote possibility — pivot_table() simply averages, or otherwise aggregates, duplicates together instead of raising an error, which makes it the safer default for real-world, messier data.

editor.html
import pandas as pd

df = pd.DataFrame({"date": ["d1", "d1", "d1"], "city": ["NYC", "NYC", "LA"], "temp": [30, 32, 60]})
print(pd.pivot_table(df, index="date", columns="city", values="temp", aggfunc="mean"))
localhost:3000

Examples

Example 01Basic Usage
import pandas as pd

df = pd.DataFrame({"date": ["d1", "d1", "d1"], "city": ["NYC", "NYC", "LA"], "temp": [30, 32, 60]})
print(pd.pivot_table(df, index="date", columns="city", values="temp", aggfunc="mean"))
Example 02Advanced Example
import pandas as pd

df = pd.DataFrame({"region": ["East", "East", "West"], "product": ["A", "A", "A"], "sales": [100, 150, 200]})
print(pd.pivot_table(df, index="region", columns="product", values="sales", aggfunc="sum"))

Best Practices

  • Use pivot_table() by default over pivot() for real-world data, since it gracefully aggregates duplicates instead of requiring strict uniqueness
  • Choose aggfunc deliberately, sum, count, mean, etc., based on what the summarized value should actually represent, rather than relying on the mean default
  • Pass margins=True when you also want row/column subtotals included automatically, instead of computing them separately

Interview Question

How does pd.pivot_table() handle the exact situation that makes df.pivot() raise an error?

Hint: Think about what pivot_table()'s extra aggfunc parameter actually does with duplicate combinations.

When the same index/columns combination appears more than once in the source data, pivot_table() collects all the values sharing that combination and applies the aggfunc, mean by default, to combine them into a single summary number for that cell, rather than requiring each combination to already be unique. Plain pivot() has no such mechanism and simply raises an error the moment it encounters a duplicate combination, since it expects a strict one-to-one mapping — pivot_table() is essentially pivot() plus an explicit, configurable answer to the question of what to do with duplicates.

Exercises

MediumPractice using pd.pivot_table() in a real scenario.
View Solution
import pandas as pd

df = pd.DataFrame({"date": ["d1", "d1", "d1"], "city": ["NYC", "NYC", "LA"], "temp": [30, 32, 60]})
print(pd.pivot_table(df, index="date", columns="city", values="temp", aggfunc="mean"))

Frequently Asked Questions

How does pd.pivot_table() handle the exact situation that makes df.pivot() raise an error?

When the same index/columns combination appears more than once in the source data, pivot_table() collects all the values sharing that combination and applies the aggfunc, mean by default, to combine them into a single summary number for that cell, rather than requiring each combination to already be unique. Plain pivot() has no such mechanism and simply raises an error the moment it encounters a duplicate combination, since it expects a strict one-to-one mapping — pivot_table() is essentially pivot() plus an explicit, configurable answer to the question of what to do with duplicates.

Related Functions

df-pivotdf-groupbydf-agg