Pandas pd.crosstab() function
pd.crosstab() is a function in the Pandas library used to **compute cross tabulations (Cross Tabulation)**. It can compute frequencies or aggregate statistics for two or more variables, producing a table similar to an Excel pivot table.
Cross tabulation is a very useful tool in statistical analysis, often used to examine the relationship between two or more categorical variables, such as counting the number of male and female employees in different departments.
Word meaning: crosstab is short for "cross tabulation", a type of statistical table that displays the joint distribution of two or more variables.
Basic syntax and parameters
pd.crosstab() is a top-level function in the Pandas library used to compute cross tabulations.
Syntax format
pd.crosstab(index, columns, values=None, aggfunc=None, margins=False, margins_name='All', dropna=True, normalize=False)
Parameter Description
- Parameters:
index - Type: array-like, Series, or list.
- Description: Data used as row indices. Can be a single column or multiple columns (a list).
- Parameters:
columns - Type: array-like, Series, or list.
- Description: Data used as column indices. Can be a single column or multiple columns (a list).
- Parameters:
values - Type: array-like or None.
- Description: Values to aggregate. If specified, it must be used together with the
aggfuncparameter.
- Parameters:
aggfunc - Type: function or string.
- Description: Aggregation function (such as 'sum', 'mean', 'count', etc.). Needed when
valuesis specified.
- Parameters:
margins - Type: boolean.
- Description: If
True, add row and column totals. Defaults toFalse。
- Parameters:
normalize - Type: boolean or 'all', 'index', 'columns'.
- Description: If
True, divide the values by the total to produce proportions (0-1). You can also specify 'index' or 'columns' to normalize by row or by column.
Function description
- Return Value: Returns a DataFrame representing the cross relationship between two or more variables.
- effect: Generates a table where rows and columns represent different categorical variables, and cells show the corresponding frequencies or aggregate values.
Example
Let us thoroughly master pd.crosstab() through a series of examples from simple to complex.
Example 1: Basic usage - cross tabulation of two categorical variables
Example
import
pandas
as
pd
1. Create employee data
employees
=
pd.
DataFrame
(
{
'department'
:
[
'Sales'
,
'Sales'
,
'Sales'
,
'Engineering'
,
'Engineering'
,
'HR'
,
'HR'
,
'Sales'
,
'Engineering'
,
'HR'
]
,
'gender'
:
[
'Male'
,
'Female'
,
'Female'
,
'Male'
,
'Male'
,
'Female'
,
'Male'
,
'Female'
,
'Female'
,
'Male'
]
}
)
(
"=== Employee data ==="
)
(
employees
)
2. Compute the cross tabulation of department and gender (frequencies)
result
=
pd.
crosstab
(
employees
[
'department'
]
,
employees
[
'gender'
]
)
(
"n=== pd.crosstab() department vs gender cross tab ==="
)
(
result
)
Expected output:
=== 员工数据 ===
department gender
0 Sales Male
1 Sales Female
2 Sales Female
3 Engineering Male
4 Engineering Male
5 HR Female
6 HR Male
7 Sales Female
8 Engineering Female
9 HR Male
=== pd.crosstab() 部门与性别交叉表 ===
gender Female Male
department
Engineering 1 2
HR 1 2
Sales 3 1
Code analysis:
- The resulting table shows the number of male and female employees in each department.
Example 2: Add row and column totals and normalization
Use margins parameter can add totals,normalize parameter can show the proportion distribution.
Example
import
pandas
as
pd
Using the employee data above
employees
=
pd.
DataFrame
(
{
'department'
:
[
'Sales'
,
'Sales'
,
'Sales'
,
'Engineering'
,
'Engineering'
,
'HR'
,
'HR'
,
'Sales'
,
'Engineering'
,
'HR'
]
,
'gender'
:
[
'Male'
,
'Female'
,
'Female'
,
'Male'
,
'Male'
,
'Female'
,
'Male'
,
'Female'
,
'Female'
,
'Male'
]
}
)
1. Add row and column totals
result_margins
=
pd.
crosstab
(
employees
[
'department'
]
,
employees
[
'gender'
]
,
margins
=
True
)
(
"=== Add totals (margins=True) ==="
)
(
result_margins
)
2. Normalize - convert to proportions
(
"n=== Overall normalization (normalize=True) ==="
)
result_norm
=
pd.
crosstab
(
employees
[
'department'
]
,
employees
[
'gender'
]
,
normalize
=
True
)
(
result_norm.
round
(
3
)
)
3. Normalize by row (each row sums to 1)
(
"n=== Row normalization (normalize='index') ==="
)
result_norm_index
=
pd.
crosstab
(
employees
[
'department'
]
,
employees
[
'gender'
]
,
normalize
=
'index'
)
(
result_norm_index.
round
(
3
)
)
4. Normalize by column (each column sums to 1)
(
"n=== Column normalization (normalize='columns') ==="
)
result_norm_col
=
pd.
crosstab
(
employees
[
'department'
]
,
employees
[
'gender'
]
,
normalize
=
'columns'
)
(
result_norm_col.
round
(
3
)
)
Expected output:
=== 添加合计 (margins=True) ===
gender Female Male All
department
Engineering 1 2 3
HR 1 2 3
Sales 3 1 4
All 5 5 10
=== 整体归一化 (normalize=True) ===
gender Female Male
department
Engineering 0.1 0.2
HR 0.1 0.2
Sales 0.3 0.1
=== 按行归一化 (normalize='index') ===
gender Female Male
department
Engineering 0.333 0.667
HR 0.333 0.667
Sales 0.75 0.25
=== 按列归一化 (normalize='columns') ===
gender Female Male
department
Engineering 0.2 0.4
HR 0.2 0.4
Sales 0.6 0.2
Code analysis:
- Normalization makes it easy to analyze proportional relationships and understand the relative distribution of gender within each department.
- Row normalization shows the percentage distribution of gender within each department.
- Column normalization shows the distribution proportion of each gender across departments.
Example 3: Multiple variables and aggregation functions
You can use multiple row/column variables and use aggregation functions to compute statistics.
Example
import
pandas
as
pd
import
numpy
as
np
1. Create sales data
sales
=
pd.
DataFrame
(
{
'region'
:
[
'North'
,
'North'
,
'South'
,
'South'
,
'East'
,
'East'
,
'West'
,
'West'
,
'North'
,
'South'
]
,
'product'
:
[
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
,
'B'
,
'A'
]
,
'quarter'
:
[
'Q1'
,
'Q1'
,
'Q1'
,
'Q1'
,
'Q2'
,
'Q2'
,
'Q2'
,
'Q2'
,
'Q2'
,
'Q2'
]
,
'sales'
:
[
100
,
150
,
200
,
180
,
120
,
160
,
190
,
170
,
140
,
210
]
}
)
(
"=== Sales data ==="
)
(
sales
)
2. Use multiple row variables
(
"n=== Cross tab of region and product (frequencies) ==="
)
result_multi
=
pd.
crosstab
(
[
sales
[
'region'
]
,
sales
[
'product'
]
]
,
sales
[
'quarter'
]
)
(
result_multi
)
3. Use values and aggfunc to compute sales
(
"n=== Sales total by region and quarter ==="
)
result_sum
=
pd.
crosstab
(
sales
[
'region'
]
,
sales
[
'quarter'
]
,
values
=
sales
[
'sales'
]
,
aggfunc
=
'sum'
)
(
result_sum
)
4. Compute the average sales
(
"n=== Average sales by region and quarter ==="
)
result_mean
=
pd.
crosstab
(
sales
[
'region'
]
,
sales
[
'quarter'
]
,
values
=
sales
[
'sales'
]
,
aggfunc
=
'mean'
)
(
result_mean.
round
(
1
)
)
Expected output:
=== 销售数据 ===
region product quarter sales
0 North A Q1 100
1 North B Q1 150
2 South A Q1 200
3 South B Q1 180
4 East A Q2 120
5 East B Q2 160
6 West A Q2 190
7 West B Q2 170
8 North B Q2 140
9 South A Q2 210
=== 区域和产品的交叉表(频次)===
quarter Q1 Q2
region product
East A 0 1
B 0 1
North A 1 0
B 1 1
South A 1 1
B 1 0
West A 0 1
B 0 1
=== 区域和季度的销售额合计 ===
quarter Q1 Q2
region
East NaN 280
North 250 140
South 380 210
West NaN 360
=== 区域和季度的平均销售额 ===
quarter Q1 Q2
region
East NaN 140.0
North 125.0 140.0
South 190.0 210.0
West NaN 180.0
Code analysis:
- Using multiple row variables (as a list) creates a cross tabulation with a multi-level index.
- Each cell shows the number of occurrences of a specific region and product combination in a specific quarter.
- Using the values and aggfunc parameters, you can compute aggregations of actual numeric values (sum, mean, etc.).
Example 4: Handling missing values
dropna parameter controls whether missing categories are included.
Example
import
pandas
as
pd
import
numpy
as
np
1. Data containing missing values
data
=
pd.
DataFrame
(
{
'A'
:
[
'a'
,
'a'
,
'b'
,
np.
nan
,
'a'
,
'b'
]
,
'B'
:
[
'x'
,
'y'
,
'x'
,
'x'
,
np.
nan
,
'y'
]
}
)
(
"=== Data containing missing values ==="
)
(
data
)
2. By default, combinations containing missing values are removed
result_drop
=
pd.
crosstab
(
data
[
'A'
]
,
data
[
'B'
]
)
(
"n=== Remove missing values by default (dropna=True) ==="
)
(
result_drop
)
3. Include missing categories
result_keep
=
pd.
crosstab
(
data
[
'A'
]
,
data
[
'B'
]
,
dropna
=
False
)
(
"n=== Include missing categories (dropna=False) ==="
)
(
result_keep
)
Expected output:
=== 包含缺失值的数据 ===
A B
0 a x
1 a y
2 b x
3 NaN x
4 a NaN
5 b y
=== 默认移除缺失值 (dropna=True) ===
B x y
A
a 1 1
b 1 1
=== 包含缺失值 (dropna=False) ===
B x y NaN
A
a 1 1 1
b 1 1 0
NaN 1 0 0
Code analysis:
- Default
dropna=Trueremoves rows and columns containing missing values, showing only valid data. - Use
dropna=Falselets you see the frequencies of combinations that include missing values.
Tip:
pd.crosstab()Suitable for analyzing relationships between categorical variables. For more complex data summaries (such as computing multiple aggregate metrics), usepd.pivot_table()function in Vue 3.
Common Pandas functions