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.
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"))2Practical Example
Here is a real-world application of pd.pivot_table() showing how it is used in production Pandas code.
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"))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.
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"))