crosstab()
crosstab counts how often each pair of category values occurs together.
In this page:
Syntax
pd.crosstab(df["column1"], df["column2"])
pd.crosstab(df["column1"], df["column2"], normalize="index")
crosstab()
pd.crosstab(a, b) produces a frequency table of two columns. Add normalize="index" for row proportions and margins=True for totals. It is a quick way to study relationships between categorical variables.
Note:
pass values and aggfunc to crosstab to aggregate a numeric column instead of counting.
Example: crosstab()
import pandas as pd
df = pd.DataFrame({"gender": ["F", "M", "F", "M", "F"], "plan": ["basic", "pro", "pro", "pro", "basic"]})
print(pd.crosstab(df["gender"], df["plan"]))
print(pd.crosstab(df["gender"], df["plan"], normalize="index").round(2))
# Output:
# plan basic pro
# gender
# F 2 1
# M 0 2
# plan basic pro
# gender
# F 0.67 0.33
# M 0.00 1.00
Related Topics
Common Mistakes
- Confusing crosstab with pivot_table
- Forgetting normalize changes counts to shares
- Passing whole DataFrames instead of columns
Chapter Summary
- crosstab counts combinations
- normalize gives proportions
- margins adds totals
- Inputs are columns or Series
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: