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

生成DataFrame除目标列外特征列所有组合子数据集(用于ML训练)

生成包含目标列的特征列组合子数据集

要实现从原DataFrame中生成包含指定目标列、且包含其余特征列所有可能组合的子数据集,可以借助Python的pandas和itertools.combinations高效完成。

代码实现

import pandas as pd
from itertools import combinations

# 构造示例原DataFrame
df = pd.DataFrame({
    'index': [0, 1, 2, 3],
    'feature1': [1, 1, 1, 1],  # 目标列
    'feature2': [2, 2, 2, 2],
    'feature3': [3, 3, 3, 3],
    'feature4': [4, 4, 4, 4]
})
target_column = 'feature1'

def get_feature_combination_dfs(df, target_col):
    # 筛选出所有特征列(排除目标列和无关的index列)
    feature_cols = [col for col in df.columns if col not in [target_col, 'index']]
    sub_dataframes = []
    
    # 生成特征列的所有2列组合(匹配示例需求)
    for feature_comb in combinations(feature_cols, 2):
        # 拼接目标列与当前特征组合
        selected_cols = [target_col] + list(feature_comb)
        sub_df = df[selected_cols].copy()
        sub_dataframes.append(sub_df)
    
    # 如果需要所有大小的特征组合(1列到全特征列),替换上面的循环为:
    # for k in range(1, len(feature_cols) + 1):
    #     for feature_comb in combinations(feature_cols, k):
    #         selected_cols = [target_col] + list(feature_comb)
    #         sub_df = df[selected_cols].copy()
    #         sub_dataframes.append(sub_df)
    
    return sub_dataframes

# 生成并输出子数据集
result_dfs = get_feature_combination_dfs(df, target_column)
for idx, sub_df in enumerate(result_dfs, 1):
    print(f"df{idx}:")
    print(sub_df)
    print("-" * 35)

输出说明

运行代码后会得到3个符合示例要求的子数据集(示例中的df4属于重复内容,应为笔误):

  • df1:包含feature1、feature2、feature3
  • df2:包含feature1、feature2、feature4
  • df3:包含feature1、feature3、feature4

如果需要覆盖所有特征列的非空组合(比如单个特征+目标列、全部特征+目标列),只需取消注释代码中对应的循环逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:20:38