Sub topic 14
Cross-tabulating two columns with crosstab
This chapter shows how to count how often each pair of values occurs across two columns and lay the counts out as a table. It assumes you can build a DataFrame, select columns, and have read the earlier chapters on value_counts, missing values, and groupby counting.
What a cross-tabulation is
DataFrame.value_counts(["city", "plan"]) counts combinations of columns, but it returns a long Series with a MultiIndex. That form is hard to scan when you want to compare one column's values against another's.
A cross-tabulation (also called a contingency table) puts the distinct values of one column down the side and the distinct values of another across the top. Each cell holds the number of rows with that pair of values. pd.crosstab builds this table in one call.
The examples use a slightly extended version of the running data. It has one missing city and an amount column, which we use later.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
"amount": [10, 20, 30, 40, 50, 60, 70],
})
table = pd.crosstab(df["city"], df["plan"])
print(table)plan free pro
city
Oslo 2 1
Paris 0 1
Rome 0 2The first argument supplies the row labels and the second supplies the column labels. Two things are worth noting.
- Pairs that never occur, such as Paris with free, appear as
0. They are not left out. - Labels are sorted, not ordered by frequency. This differs from
value_counts.
The seventh row (missing city, free plan) is absent. The next section explains why.
What goes in and what comes out
crosstab is a top-level function, not a DataFrame method. Its arguments are array-like objects of equal length, usually Series taken from one DataFrame. You pass df["city"], not the string "city". The Series names become the axis names (city and plan above). If you pass plain lists or NumPy arrays, the axes are unnamed unless you set rownames and colnames.
table = pd.crosstab(
df["city"], df["plan"],
rownames=["City"], colnames=["Plan"],
)The result is an ordinary DataFrame, so you can index it, sort it, or plot it like any other.
table.loc["Oslo", "free"] # 2, count for one pair
table.sum(axis=1) # row totals per city
table.sort_values("pro", ascending=False)Missing values
crosstab drops any row where either key is missing. That is why the row with city=None is absent from the table above, and the cell counts sum to 6, not 7.
The dropna parameter does not change this. It only controls whether columns whose entries are all NaN are excluded. It does not turn NaN into a category. To count missing keys, replace them with a label first.
with_unknown = pd.crosstab(df["city"].fillna("unknown"), df["plan"])
print(with_unknown)plan free pro
city
Oslo 2 1
Paris 0 1
Rome 0 2
unknown 1 0Compare this with value_counts(dropna=False), which reports missing values directly. With crosstab you must convert them yourself, and you should choose a label that cannot collide with a real value.
Totals and proportions
Set margins=True to add row and column totals. The new row and column are labeled All. You can rename them with margins_name.
totals = pd.crosstab(df["city"], df["plan"], margins=True, margins_name="Total")
print(totals)plan free pro Total
city
Oslo 2 1 3
Paris 0 1 1
Rome 0 2 2
Total 2 4 6The grand total is 6, because margins are computed after the missing-city row is dropped. If you compare this with len(df), which is 7, the difference is that dropped row.
The normalize parameter converts counts to fractions. It takes four kinds of value.
| Value | Each cell is divided by | What sums to 1 |
|---|---|---|
| `True` or `"all"` | The grand total | The whole table |
| `"index"` | Its row total | Each row |
| `"columns"` | Its column total | Each column |
The same values apply to the row and column labels of margins. If you pass normalize together with margins=True, the totals are normalized too.
by_city = pd.crosstab(df["city"], df["plan"], normalize="index").round(2)
print(by_city)plan free pro
city
Oslo 0.67 0.33
Paris 0.00 1.00
Rome 0.00 1.00Read this as "of Oslo's rows, 67% are on the free plan". Choose the direction by the question you are asking. To compare plan mix across cities, normalize by "index". To ask which city each plan's customers come from, normalize by "columns".
Aggregating a third column
By default crosstab counts rows. If you pass values and aggfunc, each cell holds an aggregate of a third column for that pair instead. Both must be given together.
sums = pd.crosstab(
df["city"], df["plan"],
values=df["amount"], aggfunc="sum",
)
print(sums)plan free pro
city
Oslo 40.0 60.0
Paris NaN 40.0
Rome NaN 70.0Here absent pairs are NaN, not 0, because "no rows" has no sum in this table. The counting form fills zeros, but the aggregating form does not. Add .fillna(0) if you want zeros. The result is also float, because NaN forces the dtype. Convert with .astype(int) after filling if you need integers.
Several columns on one axis
Either argument can be a list of Series. The axis then becomes a MultiIndex.
nested = pd.crosstab(df["city"], [df["plan"], df["amount"] > 30])The resulting columns are pairs such as ("free", False) and ("pro", True). This is handy for small breakdowns. Beyond that, the table gets wide and hard to read, and a long value_counts Series is usually clearer.
crosstab versus the alternatives
All three of these produce the same counts for two keys.
a = pd.crosstab(df["city"], df["plan"])
b = df.groupby(["city", "plan"]).size().unstack(fill_value=0)
c = df.pivot_table(index="city", columns="plan", values="amount",
aggfunc="count", fill_value=0)groupby drops missing keys by default, as crosstab does, so a and b agree. In c, aggfunc="count" counts non-missing amount values, so it matches only because amount has no gaps. If amount had missing entries, c would undercount.
| Tool | Best when | Notes |
|---|---|---|
| `crosstab` | You want a quick count table from two columns | Takes Series, has `margins` and `normalize` built in |
| `groupby(...).size().unstack()` | The counting is one step in a longer pipeline | Control over missing keys through `dropna=False` |
| `pivot_table` | You aggregate a value column from a DataFrame | Takes column names, not Series |
If you need missing keys as their own category without relabeling, groupby(["city", "plan"], dropna=False).size().unstack(fill_value=0) does that directly.
Common errors
- Passing column names as strings.
pd.crosstab("city", "plan")treats the strings as data and gives a table of the two words, not of your columns. Passdf["city"]. - Expecting missing values to appear. They are dropped. Use
fillnafirst. - Summing proportions across the wrong axis. Check which direction
normalizeused before you read a row or a column as a distribution. - Giving
valueswithoutaggfunc. This raises an error, and so doesaggfuncwithoutvalues. - Mismatched lengths or indexes. Series with different indexes are aligned on their index labels. Rows present in only one are dropped, which silently shrinks the counts. Take both Series from the same DataFrame.
Exercise
Using the df defined in this chapter, write a crosstab of city against plan that includes the row with the missing city as a row labeled "unknown", shows each row as a fraction of that city's total, and rounds to 2 decimals. What fractions does the "unknown" row contain?
Show answer
pd.crosstab(df["city"].fillna("unknown"), df["plan"], normalize="index").round(2). The fillna step is needed because crosstab drops rows with a missing key. The "unknown" city has one row, on the free plan, so its row is free = 1.0 and pro = 0.0.
Exercise
A colleague runs pd.crosstab(df["city"], df["plan"], margins=True) and sees a grand total of 6, but len(df) is 7. Explain the difference and give one way to make the total 7.
Show answer
The row with a missing city is dropped before counting, so only 6 rows are tabulated. Fill the missing city first, for example pd.crosstab(df["city"].fillna("unknown"), df["plan"], margins=True), which gives a grand total of 7.