You need to enable JavaScript to run this app. Python中pandas多列DataFrame如何生成两两列组合的新DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

Python中pandas多列DataFrame如何生成两两列组合的新DataFrame

实现方法

核心思路是先生成所有不重复的两两列配对,再分别计算每对列的笛卡尔积,最后合并所有结果为统一的两列结构:

import pandas as pd
from itertools import combinations

# 原始DataFrame
df = pd.DataFrame({'a':[1,2,3,3,4,4,4], 'b':[2,3,4,4,5,5,5], 'c':[5,6,7,8,5,5,5]})

res_list = []
# 遍历所有两两不重复的列组合
for col1, col2 in combinations(df.columns, 2):
    # 计算当前两列的笛卡尔积
    temp = df[[col1]].assign(tmp_key=1).merge(
        df[[col2]].assign(tmp_key=1),
        on='tmp_key'
    ).drop('tmp_key', axis=1)
    # 统一列名方便合并
    temp.columns = ['column_x', 'column_y']
    # 可选:如果需要标记所属列对,可新增字段 temp['pair'] = f'{col1}&{col2}'
    res_list.append(temp)

# 合并所有结果得到最终DataFrame
final_df = pd.concat(res_list, ignore_index=True)
  • 若不需要保留重复的笛卡尔积行,可在merge操作后追加.drop_duplicates()完成去重
  • 最终输出的final_df仅含column_x、column_y两列,完全匹配需求的结构要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 13:24:03