首页 > 解决方案 > 修改列列表以将其传递以包含或排除数据框中的列

问题描述

我想通过一个机器学习项目做一些自动化。我的 df 中有以下列。

df_col = ["Feature1", "Feature2", "Feature3", "Feature4", "Feature5"]

我想生成列名的所有组合,然后使用所有组合在循环中运行模型,以便从我的模型中消除无用的特征。我已经完成了列表中的所有组合,但是它们的格式错误,以便通过

df = df.drop([all_combinations], axis=1).

在我的 df 中生成列名(特征)组合的代码:

df_col = ["Feature1", "Feature2", "Feature3", "Feature4", "Feature5"]

import itertools  
all_combinations = []
for r in range(len(df_col) + 1):
    combinations_object = itertools.combinations(df_col, r)
    combinations_list = list(combinations_object)
    all_combinations += combinations_list
all_combinations

pandas 中特征的 drop 功能不接受给定的格式。

在此处输入图像描述

有什么办法,如何在 df 中生成所有特征组合,然后传递这些列表?

df = df.drop([all_combinations], axis=1).

标签: pandaslist

解决方案


不确定您想要什么数据类型,但如果您在字符串中包含单引号后,您可以尝试以下操作:

df_col = ["Feature1", "Feature2", "Feature3", "Feature4", "Feature5"]

# Saved as "'Feature1', 'Feature2', 'Feature3', 'Feature4', 'Feature5'"
str_list = ", ".join([f"'{val}'" for val in df_col]) 

print(str_list)

输出:

'Feature1', 'Feature2', 'Feature3', 'Feature4', 'Feature5'

推荐阅读