You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效将两个Pandas Series合并为指定笛卡尔积形式的DataFrame?

Efficiently Create Cartesian Product DataFrame from Two Pandas Series

Hey there, looks like you need to generate a Cartesian product (all possible combinations) of your two Series and turn it into a DataFrame—no problem! Here are two straightforward, efficient ways to get exactly the output you want:

Method 1: Pandas Merge with Dummy Key

This leverages Pandas' built-in merge function by creating a temporary shared key to force all combinations:

import pandas as pd

# Define your Series (setting names ensures clean column headers!)
S1 = pd.Series(["A", "B"], name="S1")
S2 = pd.Series([1, 2, 3], name="S2")

# Add a dummy key column to both Series, merge, then drop the key
result_df = S1.to_frame().assign(key=1).merge(S2.to_frame().assign(key=1), on="key").drop("key", axis=1)

print(result_df)

Method 2: Using itertools.product

If you prefer more concise code, itertools.product directly generates all possible pairs, which you can convert to a DataFrame in one go:

import pandas as pd
from itertools import product

S1 = pd.Series(["A", "B"], name="S1")
S2 = pd.Series([1, 2, 3], name="S2")

# Generate all combinations and convert to DataFrame
combinations = list(product(S1, S2))
result_df = pd.DataFrame(combinations, columns=[S1.name, S2.name])

print(result_df)

Output for Both Methods

Either approach will give you the exact DataFrame you're after:

S1  S2
0  A   1
1  A   2
2  A   3
3  B   1
4  B   2
5  B   3

Both methods work great for small-to-medium datasets. If you're dealing with very large Series, the merge method might have a slight edge since it's optimized within Pandas, but for most use cases, either is perfectly efficient.

内容的提问来源于stack exchange,提问作者jjdblast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:17:42