Knowledge base / Python
pandas pivot_table: sums, means and checks for your summary
I turn five sales observations into a region-by-product table and show why choosing the aggregation matters and when filling a gap with zero can mislead.

When several sales rows belong to the same region and product, I need to decide how to summarise them. A sum answers a different question from a mean or a count. Reshaping the table cannot make that decision for me. With pivot_table, I start by defining what one result cell should mean.
The reference here is the pandas 3.1.1 documentation available in November 2026. All data is synthetic. I explain the small results step by step using the documented aggregation rules. Both language versions use the same dataset and column names.
Choose rows, columns and aggregation first
pandas.pivot_table creates an aggregated pivot table. In a basic call, I choose the data, value column, row and column keys, and aggregation. The default aggfunc="mean" is easy to overlook, so I write my choice explicitly.
import pandas as pd
sales = pd.DataFrame({
"region": ["North", "North", "North", "South", "South"],
"product": ["A", "A", "B", "A", "B"],
"amount": [10, 30, 20, 40, 50],
})
totals = pd.pivot_table(
sales,
values="amount",
index="region",
columns="product",
aggfunc="sum",
sort=True,
)
One source row represents a sales observation in an arbitrary unit. I do not call it a customer or a unique order, because neither identifier is present. The two North/A rows are two observations that we intend to add. If they were an accidental duplicate, that issue would need attention before aggregation.
| region | product | amount |
|---|---|---|
| North | A | 10 |
| North | A | 30 |
| North | B | 20 |
| South | A | 40 |
| South | B | 50 |
Read the summed result
North/A combines 10 and 30 to give 40. North/B contains one value, 20. In South, the corresponding amounts remain 40 and 50. The result is shown below, with product columns and region rows.
| region | A | B |
|---|---|---|
| North | 40 | 20 |
| South | 40 | 50 |
The first check is straightforward: North totals 60, South totals 90 and the overall amount is 150. The five input rows must support those figures. An overall total still cannot establish that every assignment is correct. Moving sales between regions could preserve it, so I inspect a specific result cell as well.
If only regional summaries are required, omit columns. If you add another grouping key, read each resulting combination accordingly. I would add detail when it answers a user’s question. An extremely wide table can hide a simple finding as effectively as an unsuitable chart.
A mean asks a different question
Change only the aggregation:
averages = pd.pivot_table(
sales,
values="amount",
index="region",
columns="product",
aggfunc="mean",
)
North/A is now the mean of two observations: 40 divided by 2 gives 20. The remaining cells have one observation each, so their values stay at 20, 40 and 50. A comparison with the previous table should recognise that the question changed. The underlying sales did not change.
For prices of 4000, 2500 and 4100, the ordinary mean is 10600 divided by 3, approximately 3533.33. Each row carries equal weight here. If one row represents one unit sold and another represents a hundred, the mean of row prices is not automatically the average price per unit sold. Agree on the unit of analysis and weighting first.

Margins and the average-of-averages trap
The margins=True option adds summary rows and columns. The reshaping guide describes these aggregates across table slices. For a sum of our sample, the expected arrangement is:
with_totals = pd.pivot_table(
sales,
values="amount",
index="region",
columns="product",
aggfunc="sum",
margins=True,
)
| region | A | B | All |
|---|---|---|---|
| North | 40 | 20 | 60 |
| South | 40 | 50 | 90 |
| All | 80 | 70 | 150 |
With mean, the overall result is 150 divided by 5, or 30. North’s mean is 60 divided by 3, or 20. South’s is 90 divided by 2, or 45. Simply averaging 20 and 45 gives 32.5, which does not recover the overall mean. The groups contain different numbers of observations. Read a mean margin in terms of the underlying data.
Missing combinations, missing values and zero
The fill_value argument applies to the result after aggregation. Consider a separate dataset:
partial = pd.DataFrame({
"region": ["North", "South"],
"product": ["A", "B"],
"amount": [10, 50],
})
filled = pd.pivot_table(
partial,
values="amount",
index="region",
columns="product",
aggfunc="sum",
fill_value=0,
)
North/B and South/A will display zero in this table. The input only establishes that those combinations have no observations. If the source is complete and an absent row means no sales, zero is reasonable. If a source file is missing, it conceals a gap.
I also avoid treating count as an unconditional row count: Series.count counts non-missing values. Counting populated amounts requires attention to rows without an amount. Counting customers requires another decision about identifiers and uniqueness. An aggregation name cannot define the business unit for you.
Categories and the pandas version
For categorical grouping keys, observed matters. Its default changed to True in pandas 3.0. If your report depends on showing unobserved categories, set the argument deliberately and check the environment version. The main example does not define categorical keys, so its result does not depend on a full category catalogue.
Missing grouping keys need a separate decision. In the 3.1.1 documentation, dropna=True excludes groups with missing keys and also affects the rows considered for margins. Before reporting, decide whether a missing region should be an explicit control category. Dropping those rows can make a table appear more complete than the data warrants.
When to choose pivot or crosstab
DataFrame.pivot reshapes without aggregation. North/A occurs twice in our main dataset, so that operation raises an error. This is useful if you expected one value per key combination. I would investigate the duplicate rather than automatically hide it with a mean.
When your main question concerns observation counts across categories, see pandas crosstab. For changing a wide table to a long one, see pandas melt. I choose the tool after defining the intended shape and meaning of the result.
Exercise: change one observation
Imagine adding North/A with an amount of 20 to the main dataset. Predict the new sum and number of observations first. The sum rises to 60 and the count to three, while the mean remains 20. This illustrates the difference between greater volume and a change in the typical observation.
Then remove the only North/B observation and decide what the user should see. Zero, a missing value or a warning depends on completeness and the report definition. I would finish only when I can explain both a number in the table and the meaning of an empty space.
Key takeaways
How does pivot_table differ from pivot?
pivot_table aggregates rows belonging to the same combination of groups. pivot reshapes without aggregation and raises an error when an index-column combination has multiple values. Choose according to the meaning of your data.
Does fill_value=0 repair missing source data?
No. It replaces missing cells in the resulting table after aggregation. Zero is appropriate only when it matches the meaning of that cell; it does not prove that the source is complete.
Does margins=True always add up visible cells?
Margins use the selected aggregation function. With mean, they are means of the underlying data for the relevant slice, rather than an unweighted average of displayed group means.
AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.
