kmail.at
contact

elsewhere

EnglishEN
← learning

pandas · difficulty ◆◆

pandas pivot_table() — build a spreadsheet-style report grid from long rows

One call replaces groupby + unstack + rename when the output is a report, not a frame.

pandas' default pivot table does not add anything up — and that one default has put averages where totals belonged in more reports than I can count.

fully AI-generatedThis text is fully AI-generated and was published without human editorial review.

2026-10-28 · 5 min read

$ df.pivot_table()
0.5.0
added in pandas

October 24, 2011 — pivot_table enters the pandas namespace (GH 234)

0.6.0
multiple value columns

November 25, 2011 (GH 381)

11
public parameters

pandas 3.0.3 signature, self excluded

'mean'
default aggfunc

printed straight from the 3.0.3 signature

What it does

df.pivot_table() takes long, transactional rows and folds them into a grid: the values of one column become the row labels (index=), another column becomes the headers (columns=), and every cell is an aggregation of the rows that land there. Duplicates are not an error — they are the point. Two EMEA valve orders in different quarters become a single EMEA/Valve cell holding their sum, count, mean or anything else you name in aggfunc=. Optional extras that make it feel like a spreadsheet: margins=True for grand totals, fill_value=0 for empty combinations, and a dict or list for aggfunc when revenue should be summed while units are averaged.

Why it matters

Answering 'revenue by region and product' with groupby means .sum().unstack(), then renaming the axis, then chasing an index name — I checked on pandas 3.0.3 and the result of pivot_table() is literally .equals() to groupby(['region','product'])['revenue'].sum().unstack(), same values, same int64 dtypes. pivot_table() is the same machinery with the report-shaped output as the default instead of an afterthought. The trap is the signature: aggfunc defaults to 'mean', so the revenue grid you forgot to configure comes back as average order value. Money needs aggfunc='sum', stated out loud.

Example

$ sales.pivot_table(index="region", columns="product", values="revenue",
                    aggfunc="sum", margins=True, margins_name="Total")
product  Pump  Valve  Total
region                     
AMER      400    650   1050
APAC     1650   2600   4250
EMEA     1700   2550   4250
Total    3750   5800   9550

The report the finance team asked for, in one call. margins adds both the Total row and the Total column; margins_name renames the label.

$ sales.pivot_table(index="region", columns="product", values="revenue").round(0)
product   Pump   Valve
region                
AMER     400.0   650.0
APAC     825.0  1300.0
EMEA     850.0  1275.0

No aggfunc, so aggfunc='mean' ran: APAC Pump is 825 — the average of 700 and 950 — not 1650. Same call, wrong number, no warning.

$ try:
    sales.pivot(index="region", columns="product", values="revenue")
except ValueError as e:
    print("pivot():", e)
print(sales.pivot_table(index="region", columns="product", values="revenue", aggfunc="sum"))
pivot(): Index contains duplicate entries, cannot reshape
product  Pump  Valve
region              
AMER      400    650
APAC     1650   2600
EMEA     1700   2550

Same data, two methods. pivot() only reshapes and refuses to guess; pivot_table() aggregates and returns the table.

$ report = sales.pivot_table(
    index="region",
    columns="product",
    values=["revenue", "units"],
    aggfunc={"revenue": "sum", "units": "mean"},
)
print(report)
        revenue       units      
product    Pump Valve  Pump Valve
region                           
AMER        400   650   2.0   6.0
APAC       1650  2600   4.0  13.0
EMEA       1700  2550   6.5  12.5

A dict lets each value column get its own function: revenue summed, units averaged (EMEA Pump = mean of 4 and 9). Columns come back as a MultiIndex — read one with report[("units", "Pump")].

$ rev = sales.pivot_table(index="region", columns="product", values="revenue",
                        aggfunc="sum", margins=True, margins_name="Total")
share = (rev.drop(index="Total")
            .div(rev.loc["Total"], axis=1)
            .drop(columns="Total") * 100).round(1)
print(share)
product  Pump  Valve
region              
AMER     10.7   11.2
APAC     44.0   44.8
EMEA     45.3   44.0

Share of each product's total, in a two-step chain — the Total row from margins is the denominator, so no second groupby. Each column sums to 100.0.

$ cat = sales.assign(product=sales["product"].astype("category")
                   .cat.set_categories(["Pump", "Valve", "Gasket"]))
print(cat.pivot_table(index="region", columns="product", values="revenue", aggfunc="sum"))
print(cat.pivot_table(index="region", columns="product", values="revenue",
                      aggfunc="sum", observed=False, fill_value=0))
product  Pump  Valve
region              
AMER      400    650
APAC     1650   2600
EMEA     1700   2550
product  Pump  Valve  Gasket
region                      
AMER      400    650       0
APAC     1650   2600       0
EMEA     1700   2550       0

Gasket is a declared category with no sales yet. Under pandas 3.0's observed=True default it vanishes; observed=False plus fill_value=0 keeps the column as zeros, which is what a template report needs.

Common flags

index=, columns=
Which columns become row labels and headers. Pass lists to get a MultiIndex on either axis.
values=
The column(s) being aggregated. Omit it and every remaining column is aggregated — string columns get concatenated, so always pass values=.
aggfunc='mean'
The default, and the reason silently wrong reports exist. Use 'sum' for money, 'count' for orders, 'size' for rows including nulls.
aggfunc={...} or [...]
A dict maps value column → function; a list runs several functions over each value column and stacks them in the column MultiIndex.
fill_value=0
Fills cells with no matching rows. It does not invent rows — it only fills combinations the grouping already produced.
margins=True, margins_name='All'
Adds a grand-total row and column computed from the raw rows, not from the cells — for 'mean' that means the overall mean, not the mean of cell means.
observed=True
pandas 3.0 default. Unobserved categorical levels are dropped from the grid; set observed=False to keep them as zero-filled columns.

History

Added in pandas 0.5.0 (October 24, 2011)

The 0.5.0 release notes list it plainly: 'Added pivot_table convenience function to pandas namespace (GH 234)'. It arrived at the moment pandas started being used for reporting rather than just for time series, and the function came with margins and aggfunc already in place. Six weeks later, 0.6.0 (November 25, 2011) let values= take a list, so one call could tabulate several measures (GH 381).

Design note: a group-by wearing a spreadsheet's face

There is no separate pivoting engine. pivot_table() resolves the index and column keys into groupers, runs a normal groupby aggregation, then unstacks the column levels — I verified the equivalence with .equals() against a hand-written groupby().sum().unstack() on pandas 3.0.3 and it came back True, dtypes included. The spreadsheet heritage explains the defaults: 'mean' is what Excel's pivot suggests for numeric fields, and margins exists because every manager asks for a total line. pandas 3.0 extended the function further by forwarding **kwargs to aggfunc (GH 57884), so parameterised reductions like a percentile with q= can be passed straight through.

Under the hood

Under the hood: groupers in, unstack out

pivot_table() builds a list of Grouper objects from index and columns, calls the same groupby machinery every other aggregation uses, applies aggfunc, then unstacks the column levels to turn the long result into the wide grid. Aggregation itself is the Cython reduction path, so the grouping keys — not the arithmetic — dominate the runtime. margins is implemented as an extra aggregation over the whole frame, concatenated under a sentinel label, which is exactly why it reflects raw-row statistics instead of cell arithmetic. Because the result is a plain DataFrame with a possibly hierarchical column index, anything downstream that expects flat names needs .droplevel(0, axis=1) or tuple indexing.

Fun facts

Pros & cons

pros

  • + Report-shaped output by default — index, headers and totals without a groupby/unstack/rename chain.
  • + Aggregates duplicates instead of refusing them, which is the whole difference from pivot().
  • + margins, fill_value and dict aggfunc cover most of what people otherwise do in Excel.

cons

  • − aggfunc defaults to 'mean'; a revenue grid built without thinking reports averages.
  • − Multi-metric output is a 2-level column index that has to be flattened before most charts or CSV exports.
  • − It aggregates everything it is given — filter the frame first or your totals quietly include test rows.

Takeaways

  1. 1Always state aggfunc: 'sum' for money, 'count' for orders, 'size' when nulls must count as rows.
  2. 2Use margins=True for totals, then read the Total row as a raw-row aggregate, not as a sum of the cells above it.
  3. 3Reach for pivot() only when (index, columns) pairs are guaranteed unique; otherwise pivot_table() is the safer call.
  4. 4Keep categorical grids stable with observed=False plus fill_value=0, or columns will disappear when a level has no data.
  5. 5Flatten multi-metric results with .droplevel(0, axis=1) before handing them to a chart or a CSV.

Related commands

archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →

← all learning