Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Pandas · Function

pivot_table

Creates a spreadsheet-style pivot table from a DataFrame by grouping row and column keys and aggregating selected values. It supports custom aggregation, missing-value filling, totals, categorical-group control, and sorting.

How it works

Use pandas.pivot_table to group a DataFrame by row and column keys while aggregating one or more value columns. The result is a DataFrame whose row and column levels can be MultiIndex objects, with options for missing-value filling, totals, sorting, and categorical-group handling.

Syntax

pandas.pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All', observed=True, sort=True, **kwargs)

Parameters

NameTypeDescription
dataDataFrameInput pandas DataFrame object.
valueslist-like or scalar, optionalColumn or columns to aggregate.
indexcolumn, Grouper, array, or sequence of the previousKeys to group by on the pivot table index.
columnscolumn, Grouper, array, or sequence of the previousKeys to group by on the pivot table column.
aggfuncfunction, list of functions, dict, default 'mean'Function, list of functions, or dictionary used for aggregation; default is mean.
fill_valuescalar, default NoneValue used to replace missing values in the result after aggregation.
marginsbool, default FalseWhether to add partial aggregates; default is False.
dropnabool, default TrueWhether to exclude missing values from group keys; default is True.
margins_namestr, default 'All'Label for the totals row and column; default is 'All'.
observedbool, default TrueWhether to show only observed categorical groups; default is True.
sortbool, default TrueWhether to sort the result; default is True.
**kwargsdictAdditional keyword arguments.

Returns

DataFrame — an Excel-style pivot table.

Key points

  • The function returns a DataFrame arranged like a spreadsheet pivot table.
  • Grouped row or column dimensions can be represented by hierarchical MultiIndex levels.
  • values selects the column or columns whose data will be aggregated.
  • index defines the grouping keys for result rows.
  • columns defines the grouping keys for result columns.
  • A dictionary aggfunc lets each aggregated column use its own function or list of functions.

Common mistakes

  • Supplying multiple aggregation functions creates hierarchical result columns, which can change how columns must be selected.
  • With categorical groupers, observed controls whether only observed combinations or all category combinations appear.
  • fill_value replaces missing values in the aggregated result; it does not change missing values before aggregation.

Example: Aggregate sales into a pivot table

import pandas as pd

df = pd.DataFrame({
    "region": ["East", "East", "West"],
    "product": ["A", "B", "A"],
    "sales": [10, 20, 15],
})

result = pd.pivot_table(
    df,
    values="sales",
    index="region",
    columns="product",
    aggfunc="sum",
    fill_value=0,
)
print(result)

Groups sales by region and product, sums each group, and replaces missing combinations with zero.

When to use it

Business reporting

Summarize numeric measures by two or more dimensions.

Cross-tabulated analysis

Compare category combinations in a matrix layout.

Reports with margins

Produce grouped totals alongside category-level aggregates.

Interview questions

QWhat does pandas.pivot_table do?

It creates a spreadsheet-style pivot table as a DataFrame. The supplied index and columns keys define groups, and aggfunc computes the aggregate for the selected values.

Follow-up: What structure can the result have? Its row and column levels are stored in MultiIndex objects when the grouping produces multiple levels.

QHow does aggfunc work?

aggfunc defaults to 'mean'. It can also be a function, a list of functions, or a dictionary mapping columns to aggregation functions.

Follow-up: What happens with a function list? The resulting columns become hierarchical, with top-level labels inferred from the function names.

QHow do you add totals and handle missing combinations?

margins=True adds partial aggregates across categories, using the margins_name label, which defaults to 'All'. fill_value can replace missing cells after aggregation.

Follow-up: Can grouping keys be non-column arrays? Yes; index and columns accept arrays or sequences, subject to the documented grouping requirements.

  • pandas.DataFrame.pivot_table
  • pandas.pivot
  • pandas.DataFrame.pivot
  • pandas.crosstab

Source: pandas.pivot_table — pandas 3.0.6 documentation. Checked 2026-10-15.