ZetCode

Pandas Crosstab

last modified November 17, 2026 Python 3.15

A contingency table, also called a cross tabulation or frequency table, is a table that counts how often each combination of two or more categories occurs. For example, it can show how many items of each product were sold in each city. One set of categories labels the rows, another labels the columns, and each cell holds the count for that pair.

Pandas builds such tables with pd.crosstab. This article covers the basic count table, row and column totals, turning counts into proportions with normalize, grouping by more than one array, aggregating a value column with aggfunc, and the difference from pivot_table. All examples were run with pandas 3.1.1.

Frequency tables

In its simplest form pd.crosstab takes two arrays: one for the row labels and one for the column labels. It counts the rows of the DataFrame that fall into each combination and places the counts in the matching cell. The result is a DataFrame whose index and column names come from the two inputs.

crosstab_basic.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B', 'A', 'B'],
    'product': ['x', 'y', 'x', 'y', 'x', 'x']
})
print(pd.crosstab(df['city'], df['product']))

City A appears twice with product x and once with y; city B also has two x sales and one y sale. These four numbers fill the body of the table, with cities down the side and products across the top.

$ python crosstab_basic.py
product  x  y
city         
A        2  1
B        2  1

Margins

A margin is a total added along the edge of the table. Setting margins=True appends an All row with the totals for each column and an All column with the totals for each row. The bottom-right cell holds the grand total of all counted rows.

crosstab_margins.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B', 'A', 'B'],
    'product': ['x', 'y', 'x', 'y', 'x', 'x']
})
print(pd.crosstab(df['city'], df['product'], margins=True))

The All column shows three records for each city, and the All row shows four sales of x and two of y. The grand total in the corner is 6, which equals the number of rows in the original DataFrame.

$ python crosstab_margins.py
product  x  y  All
city              
A        2  1    3
B        2  1    3
All      4  2    6

Normalizing

Counts can be converted into proportions with the normalize parameter. The value 'all' divides every cell by the grand total, 'index' divides each cell by the total of its row, and 'columns' divides each cell by the total of its column. The three choices answer three different questions: share of everything, share within a row, or share within a column.

crosstab_normalize.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B', 'A', 'B'],
    'product': ['x', 'y', 'x', 'y', 'x', 'x']
})
print(pd.crosstab(df['city'], df['product'], normalize='all'))
print()
print(pd.crosstab(df['city'], df['product'], normalize='index'))
print()
print(pd.crosstab(df['city'], df['product'], normalize='columns'))

With normalize='all' the six records become fractions of 6, so a count of 2 appears as 0.333333. With 'index' each row sums to 1, giving 0.666667 and 0.333333. With 'columns' each column sums to 1, and since x and y are evenly split between the cities every entry is 0.5.

$ python crosstab_normalize.py
product         x         y
city                       
A        0.333333  0.166667
B        0.333333  0.166667

product         x         y
city                       
A        0.666667  0.333333
B        0.666667  0.333333

product    x    y
city             
A        0.5  0.5
B        0.5  0.5

Multiple grouping arrays

More than one array can label the rows or the columns. We pass a list such as [df['city'], df['year']] as the first argument, and Pandas creates a hierarchical row index combining the two. Each row then counts one combination of city, year and product.

crosstab_multi.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B', 'A', 'B'],
    'product': ['x', 'y', 'x', 'y', 'x', 'x'],
    'year': [2024, 2024, 2024, 2024, 2025, 2025]
})
print(pd.crosstab([df['city'], df['year']], df['product']))

The index now has two levels, city and year. For city A in 2024 there is one x and one y sale, while in 2025 there is one x and no y. The same pattern holds for city B. This is the same hierarchical index idea used by the MultiIndex tutorial.

$ python crosstab_multi.py
product    x  y
city year      
A    2024  1  1
     2025  1  0
B    2024  1  1
     2025  1  0

values and aggfunc

Instead of counting rows, we can aggregate the numbers from a chosen column. We pass that column as values and name the summary as aggfunc, for example 'sum'. Each cell then holds the sum of the value column for the rows in that category pair, rather than a count.

crosstab_values.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B', 'A', 'B'],
    'product': ['x', 'y', 'x', 'y', 'x', 'x'],
    'sales': [10, 20, 30, 40, 50, 60]
})
print(pd.crosstab(df['city'], df['product'], values=df['sales'], aggfunc='sum'))

For city A and product x the two sales of 10 and 50 add up to 60. For city B and product x the sales 30 and 60 add up to 90. An aggregate function named as a string, such as 'mean' or 'max', can be used in place of 'sum'.

$ python crosstab_values.py
product   x   y
city           
A        60  20
B        90  40

How this differs from pivot_table

The pivot table tutorial covers pivot_table, which also arranges data by row and column keys. The key difference is the default: crosstab counts occurrences and needs only two arrays, while pivot_table works on a DataFrame and needs a values column plus an aggregation, using the mean when no aggfunc is given. The example makes the contrast visible on the same four rows.

crosstab_vs_pivot.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B'],
    'product': ['x', 'y', 'x', 'y'],
    'sales': [10, 20, 30, 40]
})
print(pd.crosstab(df['city'], df['product']))
print()
print(df.pivot_table(index='city', columns='product', values='sales', aggfunc='sum'))

Here crosstab reports one occurrence in each cell, because each city-product pair appears once. The pivot_table call reports the sales amounts 10, 20, 30 and 40 instead. Use crosstab for counts and pivot_table when you need to aggregate a particular column.

$ python crosstab_vs_pivot.py
product  x  y
city         
A        1  1
B        1  1

product   x   y
city           
A        10  20
B        30  40

Source

Pandas crosstab Documentation, Pandas DataFrame.pivot_table Documentation, and Pandas Reshaping Documentation

In this article we have built frequency tables with pd.crosstab, added totals with margins, converted counts to proportions with normalize, grouped by several arrays, summed a value column with aggfunc, and compared the result with pivot_table. For the closely related reshaping operations see Pandas pivot table and Pandas melt and pivot.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pandas tutorials.