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

Pandas · Function

pd.crosstab

pandas.crosstab computes a cross-tabulation of two or more factors. It produces frequency counts by default, or aggregates supplied values when paired with aggfunc.

How it works

pandas.crosstab groups the supplied row and column factors and returns a DataFrame containing their cross-tabulation. With only index and columns it counts observations; supplying values together with aggfunc instead aggregates values within each factor combination. Optional normalization, margins, labels, and missing-category handling customize the result.

Syntax

pandas.crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name='All', dropna=True, normalize=False)

Parameters

NameTypeDescription
indexarray-like, Series, or list of arrays/SeriesArray-like, Series, or list of arrays/Series; factors defining the rows.
columnsarray-like, Series, or list of arrays/SeriesArray-like, Series, or list of arrays/Series; factors defining the columns.
valuesarray-like, optionalOptional values aggregated within factor combinations; requires aggfunc.
rownamessequence, default NoneOptional row labels; must match the number of row arrays.
colnamessequence, default NoneOptional column labels; must match the number of column arrays.
aggfuncfunction, optionalOptional aggregation function; requires values.
marginsbool, default FalseWhether to add row and column subtotals.
margins_namestr, default 'All'Label used for added margins.
dropnabool, default TrueWhether to omit columns whose entries are all NaN.
normalizebool or {'all', 'index', 'columns'} or {0, 1}, default FalseNormalization mode: False, True-like values, 'all', 'index', 'columns', 0, or 1.

Returns

DataFrame — Cross tabulation of the data.

Key points

  • Use it to arrange the relationship between multiple categorical factors in a DataFrame.
  • With index and columns only, cells contain combination counts.
  • The index argument supplies the factor or factors defining result rows.
  • The columns argument supplies the factor or factors defining result columns.
  • values provides the data to summarize inside each factor combination.
  • margins=True appends row and column subtotal results.
  • normalize converts counts or aggregates into proportions according to the selected normalization mode.

Common mistakes

  • When values is provided, aggfunc must also be supplied.
  • An aggregation function cannot be used without providing values.
  • rownames must contain one label for each row factor.
  • colnames must contain one label for each column factor.

Example: Count combinations with a cross-tabulation

import pandas as pd

colors = pd.Series(["red", "blue", "red", "blue"])
shapes = pd.Series(["circle", "circle", "square", "square"])

result = pd.crosstab(colors, shapes)
print(result)

Counts each combination of the two categorical inputs and returns those counts in a DataFrame.

When to use it

Frequency tables

Summarize records by two categorical dimensions.

Grouped aggregation

Calculate a metric for each row-and-column category pair.

Proportion analysis

Report shares rather than raw counts.

Marginal totals

Show category subtotals alongside the cross-tabulation.

Interview questions

QWhat does pandas.crosstab do by default?

It creates a DataFrame cross-tabulation for two or more factors. Without values and aggfunc, each cell is the frequency of a row-factor and column-factor combination.

Follow-up: How would you compute a statistic instead of a count? Pass values and an aggregation function, such as aggfunc='mean'.

QHow do you include totals?

Set margins=True to add row and column subtotals. The subtotal label is controlled by margins_name, whose default is 'All'.

Follow-up: How would you rename the subtotal label? Pass a different string through margins_name.

QHow can the output be normalized?

normalize divides values by a sum and accepts False, True-like modes represented by 'all', 'index', or 'columns', as well as 0 or 1. This supports overall, row-wise, or column-wise proportions.

Follow-up: Which setting gives row percentages? Use normalize='index'.

  • pandas.pivot_table
  • pandas.DataFrame.pivot_table
  • pandas.get_dummies

Source: pandas.crosstab. Checked 2026-10-15.