← Back to Pandas Course | Chapter 7: Grouping & Aggregation | Lesson 6 of 7

crosstab()

crosstab counts how often each pair of category values occurs together.

In this page:

  1. crosstab()
Syntax
python
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()

python
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
  1. Confusing crosstab with pivot_table
  2. Forgetting normalize changes counts to shares
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.