Sub topic 13
Counting combinations with crosstab
This chapter assumes you know pivot_table, groupby, and how to select DataFrame columns. Here you will build a frequency table with pd.crosstab. It counts how often each pair of category values occurs.
What crosstab does
pd.crosstab takes two or more label sequences, usually columns, and returns a table. Rows hold the unique values of the first sequence, and columns hold the unique values of the second. Each cell counts the rows where that pair appears together.
import pandas as pd
orders = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"product": ["tea", "tea", "coffee", "tea", "coffee", "coffee"],
"paid": [5, 5, 4, 5, 4, 6],
})
counts = pd.crosstab(orders["store"], orders["product"])
print(counts)Store A has two tea orders and one coffee order. Store B has one tea order and two coffee orders. Pairs that never occur get 0, so you do not need fill_value.
crosstab is a function on the pd module, not a DataFrame method. You pass it the columns themselves, not column names.
Totals and proportions
The margins argument adds row and column totals, as it does in pivot_table. The normalize argument converts counts to shares.
print(pd.crosstab(
orders["store"], orders["product"],
margins=True, margins_name="total",
))
print(pd.crosstab(
orders["store"], orders["product"],
normalize="index",
))The normalize argument accepts these values:
| Value | Each cell is divided by |
|---|---|
| `"index"` | its row total, so every row sums to 1 |
| `"columns"` | its column total, so every column sums to 1 |
| `"all"` | the grand total |
| `True` | the grand total, same as `"all"` |
With normalize="index", store A shows about 0.33 for coffee and 0.67 for tea. Use "index" when you want to compare the product mix of each store.
Aggregating values instead of counting
Pass values and aggfunc together to aggregate a column instead of counting rows.
total_paid = pd.crosstab(
orders["store"],
orders["product"],
values=orders["paid"],
aggfunc="sum",
)
print(total_paid)Passing only one of the two raises a ValueError. Combinations that never occur become NaN, not 0, because there is nothing to sum. Add .fillna(0) if you need zeros.
crosstab versus pivot_table
The same counts are available from pivot_table, but it needs more arguments.
same = orders.pivot_table(
index="store",
columns="product",
values="paid",
aggfunc="count",
fill_value=0,
)
print(same)Here count tallies non-missing paid values. If paid had missing entries, those rows would not be counted. crosstab counts rows regardless of missing values in a third column.
| Situation | Better choice |
|---|---|
| Counting pairs of categories | `crosstab` |
| Shares of a row, column, or total | `crosstab` with `normalize` |
| Aggregating one column with many functions | `pivot_table` |
| Working from a DataFrame with column names | `pivot_table` |
Common errors
- Passing column names as strings.
pd.crosstab("store", "product")treats the strings as the labels themselves and fails. Passorders["store"], or usepd.crosstab(index=orders["store"], columns=orders["product"]). - Expecting
NaNrows to be counted. By default,crosstabdrops rows where either label is missing. Clean or fill those labels first if they matter. - Forgetting that
normalizechanges the values to floats, so the table no longer holds integer counts.
Exercise
Using the orders DataFrame, write one call that gives the share of each store's orders going to each product, with totals added, and explain why normalize="columns" would answer a different question.
Show answer
Call pd.crosstab(orders["store"], orders["product"], normalize="index", margins=True). Each row then shows the share of that store's orders per product. The total row gives the overall mix of products. With normalize="columns", each product column sums to 1. That shows how a product's orders split across stores, not how each store's orders split across products.