Sub topic 13
Counting combinations with crosstab
This chapter assumes you have read the earlier chapters on pivot, pivot_table, and flattening column labels. You should also be comfortable with groupby and size. Here you will learn how pd.crosstab builds frequency tables, when it beats pivot_table, and how to turn its output back into tidy data.
What crosstab does
A cross-tabulation counts how often each combination of two or more categorical variables occurs. The rows of the result are the values of one variable. The columns are the values of another. Each cell holds the number of source rows with that pair of values.
crosstab is a top-level function, pd.crosstab, not a DataFrame method. It takes array-like inputs, usually Series, instead of a DataFrame plus column names.
The examples in this chapter share one dataset and one session.
import pandas as pd
orders = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"channel": ["web", "web", "shop", "shop", "shop", "web"],
"month": ["jan", "feb", "jan", "jan", "jan", "feb"],
"amount": [10, 20, 30, 40, 50, 60],
})
counts = pd.crosstab(orders["store"], orders["channel"])
print(counts)The output is:
channel shop web
store
A 1 2
B 2 1Store A had one shop order and two web orders. The axis labels store and channel come from the name attribute of the Series you passed in. Values are sorted, so shop comes before web.
Crosstab compared with groupby and pivot_table
You could produce the same table with tools you already know:
by_group = orders.groupby(["store", "channel"]).size().unstack(fill_value=0)
print(by_group)This gives the same numbers. crosstab is shorter when counting is the goal, and it adds options for percentages and totals.
| Feature | `pd.crosstab` | `pivot_table` | `groupby(...).size().unstack()` |
|---|---|---|---|
| Input | Series or arrays | DataFrame plus column names | DataFrame plus column names |
| Default cell value | Count of rows | Mean of `values` | Count of rows |
| Missing combinations | Count is 0 | `NaN` unless `fill_value` is set | `NaN` unless `fill_value` is set |
| Proportions | `normalize=` | Manual division | Manual division |
| Totals | `margins=True` | `margins=True` | Manual |
| `fill_value` parameter | No | Yes | Through `unstack` |
Internally, crosstab builds a temporary DataFrame from your inputs and calls pivot_table. That is why its options mirror pivot_table, and why it has no fill_value.
Totals with margins
Set margins=True to add a total row and column. Use margins_name to rename them.
with_totals = pd.crosstab(
orders["store"], orders["channel"],
margins=True, margins_name="total",
)
print(with_totals)The output is:
channel shop web total
store
A 1 2 3
B 2 1 3
total 3 3 6The bottom-right cell, 6, equals the number of rows in orders. This holds only when no row has a missing key, as described in the gotchas below.
Proportions with normalize
The normalize parameter converts counts to fractions. It accepts these values:
"index"(or1... see the note below) divides each row by its row total, so every row sums to 1."columns"divides each column by its column total."all"divides every cell by the grand total.Trueis the same as"all".
row_share = pd.crosstab(
orders["store"], orders["channel"], normalize="index"
).round(2)
print(row_share)The output is:
channel shop web
store
A 0.33 0.67
B 0.67 0.33Read this as "what share of each store's orders came through each channel". Switching to normalize="columns" would instead answer "what share of each channel's orders came from each store". Choose the direction by deciding which total should equal 100%.
Aggregating a value column
By default every cell is a count. Pass values and aggfunc together to aggregate a column instead. Both are required together. Pandas raises an error if you give aggfunc without values, or the reverse.
avg_amount = pd.crosstab(
orders["store"], orders["channel"],
values=orders["amount"], aggfunc="mean",
)
print(avg_amount)The output is:
channel shop web
store
A 30.0 15.0
B 45.0 60.0When you aggregate values, combinations that never occur become NaN, not 0, because there is nothing to average. There is no fill_value argument, so fill afterward with .fillna(0). At that point pivot_table is usually the clearer tool, because it lets you name columns of a DataFrame directly and supports fill_value.
Several variables on one axis
Pass a list to index or columns to get a MultiIndex, just as with pivot_table.
detail = pd.crosstab(
index=[orders["store"], orders["month"]],
columns=orders["channel"],
)
print(detail)The output is:
channel shop web
store month
A feb 0 1
jan 1 1
B feb 0 1
jan 2 0The row labels have two levels. Store B had no web orders in January, so that cell is 0. A count-based crosstab fills it for you, which is a real advantage over groupby().size().unstack() without fill_value.
Naming axes
If you pass something without a name, such as a plain list or NumPy array, pandas labels the axes row_0 and col_0. Use rownames and colnames to set clear labels.
named = pd.crosstab(
orders["store"].to_numpy(),
orders["channel"].to_numpy(),
rownames=["shop_id"],
colnames=["sales_channel"],
)
print(named)Both parameters take lists, one name per input array, even when there is only one.
Returning to tidy data
A crosstab is a wide, display-oriented table. Before merging it with other data or plotting it, convert it back to ordinary columns. This uses the same steps you learned for pivot.
flat = counts.reset_index()
flat.columns.name = None
print(flat)
tidy = counts.stack().reset_index(name="orders")
print(tidy)The first result has plain columns store, shop, and web. The second is long format with one row per store and channel pair, so four rows, and an orders column holding the counts. stack keeps the zero counts, so every combination is present.
Gotchas and edge cases
- Missing keys are dropped. Rows where the index or column value is
NaNdo not appear anywhere in the table. The grand total can therefore be smaller thanlen(df). Check withdf[["store", "channel"]].isna().sum()if the totals look low. - Column order is sorted, not data order. Use
.reindex(columns=[...])to set a custom order such as["jan", "feb"]. - Unused categories. With
dropna=False, rows and columns whose entries are allNaNstay in the result. With the defaultdropna=Truethey are removed. - Mixed-up name lookups.
pd.crosstab("store", "channel")does not look up columns. Strings are not treated as column names, so pass the Series. - Float results from aggregation. Any
NaNin the table turns integer values into floats. Call.fillna(0).astype(int)after filling if you need integers. - Large cardinality. Crosstabs of columns with thousands of distinct values produce huge, mostly empty tables. Use
groupby(...).size()and keep the long form in that case.
Choosing a layout
Use crosstab when the question is "how many of each combination" or "what share". Use pivot_table when the cells hold a numeric summary of a column, especially if you need fill_value. Use groupby when the grouping needs extra steps before reshaping. Whichever you choose, convert to long format with stack and reset_index when the next step is plotting or joining.
Exercise
Using the orders DataFrame from this chapter, produce a table with one row per store and one column per month, where each row shows the share of that store's orders in each month, rounded to two decimals. Why does each row sum to 1?
Show answer
Use pd.crosstab(orders["store"], orders["month"], normalize="index").round(2). The result has feb and jan columns, with 0.33 and 0.67 for both stores. normalize="index" divides each count by its row total, so the shares in every row add up to 1 (up to rounding).
Exercise
A count-based crosstab shows 0 for a combination that never occurs, but a crosstab with values=orders["amount"] and aggfunc="sum" shows NaN. Explain why, and write one line that replaces the NaN values with integer zeros.
Show answer
A count of nothing is 0, but a sum or mean needs at least one value, so pandas has no result for an empty cell and reports NaN. Fix it afterward: pd.crosstab(orders["store"], orders["channel"], values=orders["amount"], aggfunc="sum").fillna(0).astype(int). The astype(int) is needed because NaN forces the table to floats.