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

如何用Pandas实现以首列为标识的DataFrame笛卡尔积扩展?

实现col1与col2、col3的全组合(笛卡尔积)

你想要的其实是让col1列的每个值,都和col2、col3列的所有行做配对,生成笛卡尔积结构的DataFrame,下面给你两种简单高效的实现方式:

方法一:纯Pandas操作(merge+辅助列)

这种方法不需要额外导入库,完全用Pandas原生功能实现,适合日常数据处理场景:

import pandas as pd

# 原DataFrame
df = pd.DataFrame({'col1':list('abc'), 'col2':list('xyz'), 'col3':[10,20,30]})

# 提取col2和col3的所有行(原数据里已是唯一组合,直接取用即可)
df_others = df[['col2', 'col3']]
# 给col1单独生成带辅助列的DataFrame
df_col1 = df[['col1']].assign(key=1)
# 给col2/col3的DataFrame也加上相同的辅助列
df_others = df_others.assign(key=1)

# 通过辅助列merge生成笛卡尔积,最后删除辅助列
result = df_col1.merge(df_others, on='key').drop('key', axis=1)
print(result)

运行后输出的结果就是你想要的结构:

col1 col2  col3
0    a    x    10
1    a    y    20
2    a    z    30
3    b    x    10
4    b    y    20
5    b    z    30
6    c    x    10
7    c    y    20
8    c    z    30

方法二:用itertools.product生成组合

如果习惯用Python标准库的工具,这种方法逻辑更直观,适合需要灵活控制组合规则的场景:

import pandas as pd
from itertools import product

# 原DataFrame
df = pd.DataFrame({'col1':list('abc'), 'col2':list('xyz'), 'col3':[10,20,30]})

# 提取col1的所有值,以及col2和col3的配对列表
col1_values = df['col1'].tolist()
other_pairs = list(zip(df['col2'], df['col3']))

# 生成所有可能的笛卡尔积组合
all_combinations = product(col1_values, other_pairs)

# 转换为目标结构的DataFrame
result = pd.DataFrame(
    [(c1, c2, c3) for c1, (c2, c3) in all_combinations],
    columns=['col1', 'col2', 'col3']
)
print(result)

这个方法的输出和第一种完全一致,两种方式可以根据你的代码习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:06:56