pandas - 修改列列表以将其传递以包含或排除数据框中的列
问题描述
我想通过一个机器学习项目做一些自动化。我的 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).
解决方案
不确定您想要什么数据类型,但如果您在字符串中包含单引号后,您可以尝试以下操作:
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'
推荐阅读
- ios - 在 Swift 中使用 RLMResults 的正确方法是什么?
- twig - Grav 模板 - Twig 未列出子页面
- javascript - 尽管函数返回 false,但 Array.filter() 不过滤元素
- linux - lfs gcc-7.3.0 -Pass 2 error C 无法创建可执行文件
- php - 包含两个参数的 Laravel 函数
- excel - 根据列 a 列 d 的值比较来自两个工作表的数据
- python-3.x - 一起添加 JSON 数据
- android - 如何在 C for Android 中正确连接蓝牙服务器?
- arduino-uno - ARDUINO 蜂鸣器在不应该的时候播放声音
- c# - 将项目从 OutSystems 转换为 C# Visual Studio 解决方案