如何高效将两个Pandas Series合并为指定笛卡尔积形式的DataFrame?
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

