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

如何基于Pandas DataFrame非零列共存关系生成列名两两组合的新DataFrame

实现方案

核心逻辑

  • 逐行提取原始DataFrame中值不为0的列名列表
  • 对每个列名列表生成不重复的两两组合
  • 汇总所有组合后转换为新的DataFrame

代码实现

import pandas as pd
from itertools import combinations

# 替换为你自己的原始DataFrame
df = pd.read_csv("your_file.csv") # 或其他方式构造的df

result_list = []
for _, row in df.iterrows():
    # 筛选当前行非0值对应的列名
    valid_cols = row[row != 0].index.to_list()
    # 生成两两组合,长度固定为2
    for pair in combinations(valid_cols, 2):
        result_list.append(pair)

# 生成最终的两列DataFrame
new_df = pd.DataFrame(result_list, columns=["col1", "col2"])

优化说明

  • 数据量小于10万行时,上述写法可读性最高,调试成本低
  • 数据量较大时,可以用df.apply替换逐行遍历提升运行效率:
def get_pairs(row):
    valid_cols = row[row != 0].index.to_list()
    return list(combinations(valid_cols, 2))

all_pairs = df.apply(get_pairs, axis=1).explode().dropna().to_list()
new_df = pd.DataFrame(all_pairs, columns=["col1", "col2"])
  • 如果需要保留正反顺序的组合(如(A,B)和(B,A)都算有效行),将combinations替换为permutations即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:36:06