Sub topic 11
Cross joins for all combinations
This chapter covers the cross join, which pairs every row of one DataFrame with every row of another. It assumes you can already run merge on keys, read the _x and _y suffixes, and reason about row counts for one-to-many keys from earlier chapters.
What a cross join does
Every join so far matched rows by comparing key values. A cross join has no key. It produces the Cartesian product of the two tables: each left row is combined with each right row.
If the left table has m rows and the right table has n rows, the result has m * n rows. Its columns are all the left columns followed by all the right columns.
Typical uses:
- Building a complete grid of options, such as every size with every color.
- Building a scaffold of every store and month, so missing combinations show up as explicit rows.
- Generating candidate pairs, such as every pair of players, which you then filter.
Using how="cross"
Since pandas 1.2, merge accepts how="cross". You pass no key arguments.
import pandas as pd
sizes = pd.DataFrame({"size": ["S", "M", "L"]})
colors = pd.DataFrame({"color": ["red", "blue"]})
combos = sizes.merge(colors, how="cross")
print(combos)
print(len(combos))The output has six rows. The left table's order is preserved. Each size appears once for every color, in the order the colors appear in colors.
The function form pd.merge(sizes, colors, how="cross") does the same thing. DataFrame.join also accepts it, as sizes.join(colors, how="cross").
The result gets a new index
The index of the result is a fresh RangeIndex starting at 0. The index labels of the inputs are discarded. This differs from index-based joins, where labels carry through. If your input indexes hold information, move it into columns first with reset_index().
Keys are not allowed
A cross join has no key to match, so pandas rejects any key argument. Passing on, left_on, right_on, left_index, or right_index with how="cross" raises MergeError.
try:
sizes.merge(colors, on="size", how="cross")
except pd.errors.MergeError as err:
print("Rejected:", type(err).__name__)Predicting the row count
The count is always len(left) * len(right), with no exceptions. Duplicate rows are not collapsed. If sizes listed "M" twice, you would get two M rows for each color.
An empty input gives an empty result. The columns are still present, but there are no rows.
empty = pd.DataFrame({"color": pd.Series([], dtype="object")})
print(sizes.merge(empty, how="cross").shape)This prints (0, 2). That matters in pipelines where a filter upstream can leave a table with no rows. The cross join will not fail, but everything downstream gets an empty table.
Overlapping column names
The suffix rules still apply. If both tables have a column with the same name, pandas appends _x and _y by default. You can pick clearer names with suffixes.
players = pd.DataFrame({"player": ["Ana", "Ben", "Chen"]})
pairs = players.merge(players, how="cross", suffixes=("_a", "_b"))
print(pairs.shape)Merging a table with itself like this gives 9 rows, including each player paired with themselves and both orderings of each pair. You usually want only distinct, unordered pairs, so filter afterward.
unique_pairs = pairs[pairs["player_a"] < pairs["player_b"]]
print(unique_pairs.reset_index(drop=True))The comparison player_a < player_b removes self-pairs, because a name is never less than itself. It also keeps only one ordering of each pair. The result has three rows: Ana with Ben, Ana with Chen, and Ben with Chen. For n players, this leaves n * (n - 1) / 2 rows.
Worked example: a complete store-by-month grid
A common use is making missing data visible. Suppose the sales log has no row for months when a store sold nothing. A report would then skip those months. You can build a complete scaffold with a cross join, then left-merge the real data onto it.
stores = pd.DataFrame({"store": ["North", "South"]})
months = pd.DataFrame({"month": ["2026-01", "2026-02", "2026-03"]})
sales = pd.DataFrame({
"store": ["North", "North", "South"],
"month": ["2026-01", "2026-03", "2026-02"],
"revenue": [500.0, 620.0, 430.0],
})
grid = stores.merge(months, how="cross")
full = grid.merge(sales, on=["store", "month"], how="left")
full = full.fillna({"revenue": 0})
print(full)The grid has 2 × 3 = 6 rows. The left merge on both keys attaches revenue where a sale exists. The three missing combinations get NaN, which fillna replaces with 0.
Both steps matter:
- The cross join decides which rows must exist.
- The left merge keeps all of those rows, because a left join never drops left rows.
If you used an inner merge for the second step, you would lose the missing combinations again and end up with the original three rows.
Cross join versus a dummy key
Before pandas 1.2, there was no how="cross". The usual workaround was to add a constant column to both tables and merge on it.
legacy = (
sizes.assign(_k=1)
.merge(colors.assign(_k=1), on="_k")
.drop(columns="_k")
)
print(legacy.equals(combos))This prints True. You will still see this pattern in older code. It works in any version, but how="cross" is clearer and cannot leave a stray helper column behind. Prefer how="cross" unless you must support pandas older than 1.2.
Failure modes
Size explosion
The product grows fast. Two tables of 1,000 rows give 1,000,000 rows. Two tables of 100,000 rows give 10 billion, which will not fit in memory. A cross join can fail by exhausting memory, or it can work and then make every later step slow.
Check the size before you run it.
def cross_size(left, right):
return len(left) * len(right)
print(cross_size(stores, months))If the product is large, consider these options:
- Reduce each side first. Drop duplicates with
drop_duplicates()and filter to the rows you need before crossing. - If you will filter the result anyway, ask whether a keyed merge can express the same condition. A merge on a shared column creates only matching pairs, so it never builds the full product.
- Process one chunk of the left table at a time. Filter each chunk's result and concatenate the filtered pieces.
Unintended duplicates
Because duplicates multiply, a left table with repeated rows inflates the result. Run drop_duplicates() on dimension-style inputs, such as lists of stores or sizes, before crossing them. Assert the expected size afterward.
assert len(grid) == stores["store"].nunique() * months["month"].nunique()Choosing it by mistake
If you reach for a cross join and then immediately filter on equality, such as df[df["a"] == df["b"]], you built an expensive inner merge. Use merge(on=...) instead. Cross joins fit best when there is no equality condition, such as when you want all combinations or a range or inequality comparison.
Choosing between the tools
| Task | Tool |
|---|---|
| Match rows by equal key values | `merge` with `on` |
| Match rows by index label | `join` |
| Stack tables with the same columns | `concat` |
| Pair every row with every row | `merge(how="cross")` |
| Match each row to the nearest earlier key | `merge_asof` |
Exercise
A table products has 4 rows and a table regions has 5 rows. You run products.merge(regions, how="cross"). How many rows and how many columns does the result have if products has 3 columns and regions has 2 columns, with no shared column names? What happens if you add on="region_id"?
Show answer
The result has 4 * 5 = 20 rows and 3 + 2 = 5 columns. Adding on="region_id" with how="cross" raises pd.errors.MergeError, because a cross join does not accept any key arguments.
Exercise
You have employees with a column name (6 distinct names). Write code that produces every unordered pair of different employees, with columns name_a and name_b, and state how many rows you expect.
Show answer
Code: pairs = employees.merge(employees, how="cross", suffixes=("a", "b")) pairs = pairs[pairs["namea"] < pairs["nameb"]].reset_index(drop=True) The cross join gives 6 6 = 36 rows. The filter keeps one ordering of each pair and removes self-pairs, leaving 6 5 / 2 = 15 rows.