Sub topic 14
Cross-tabulating two columns with crosstab
This chapter assumes you know value_counts and how pandas treats missing values. pd.crosstab counts how often each pair of values from two columns occurs. It lays the counts out as a table, with one column's values down the side and the other's across the top.
Basic usage
The examples use the same data as the earlier chapters.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
table = pd.crosstab(df["city"], df["plan"])
print(table)The output is:
plan free pro
city
Oslo 2 1
Paris 0 1
Rome 0 2The first argument supplies the rows and the second supplies the columns. Each cell is the number of source rows with that city and plan. Combinations that never occur show as 0, not as missing.
The row with the missing city is absent from the table. crosstab leaves out any row where either input is missing. The total of the cells is therefore 6, not 7.
Relation to value_counts
crosstab gives the same numbers as df.value_counts(["city", "plan"]), but reshaped. The value_counts version is a long Series with a MultiIndex. The crosstab version is a wide table. Both drop rows with a missing value in either column.
long_form = df.value_counts(["city", "plan"])
wide_form = long_form.unstack(fill_value=0)wide_form matches table. Use the long form when you want to sort or filter pairs. Use the wide form when you want to read or compare the pairs.
Totals and proportions
Two arguments cover most needs.
| Argument | Effect |
|---|---|
| `margins=True` | Adds an `All` row and an `All` column with totals |
| `normalize="index"` | Divides each row by its row total |
| `normalize="columns"` | Divides each column by its column total |
| `normalize=True` | Divides every cell by the grand total |
totals = pd.crosstab(df["city"], df["plan"], margins=True)
row_shares = pd.crosstab(df["city"], df["plan"], normalize="index")In totals, the All row shows 2 free and 4 pro, and the grand total is 6. In row_shares, the Oslo row is about 0.667 free and 0.333 pro. Each row sums to 1, so you can read it as "of the customers in this city, what share is on each plan".
Keeping missing values
Because crosstab drops incomplete rows, fill the gaps first if you want them visible.
filled = pd.crosstab(df["city"].fillna("unknown"), df["plan"])The table now has an unknown row with 1 free and 0 pro. The dropna argument of crosstab does not do this. It only removes columns whose entries are all zero or missing, and it never restores rows with missing inputs.
Common errors
- Passing column names as strings, such as
pd.crosstab("city", "plan"). Without adata=argument,crosstabexpects the Series themselves, as indf["city"]. - Expecting rows with a missing value to be counted. Fill them first or compare against
groupby(...).size(). - Using
normalize=Truewhen you want per-row shares. Use"index"for that.
Exercise
Using the df above, which call gives the share of each city's customers on each plan, and what is the Paris row?
Show answer
pd.crosstab(df["city"], df["plan"], normalize="index"). The Paris row is 0.0 for free and 1.0 for pro, because its only customer is on the pro plan.