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

如何高效保留DataFrame中指定FT列并删除其余FT列?

问题:保留指定FT列,删除其余FT列

原始DataFrame结构示例:

FT1       FT2      ...   FT32      Style       Rank    ...
0   0.02      0.01           0.01      Black       7
1   0.01      0.04           0.01      Death       2
2   0.01      0.01           0.01      Hardcore    6
3   0.04      0.01           0.02      Grindcore   1
4   0.02      0.02           0.02      Deathcore   4
...

需求:保留索引在FT_index=[1,4,5,7]中的FT列,删除所有其他FT列,同时保留Style、Rank等非FT列,处理后结果如下:

FT1       FT4      FT5      FT7      Style       Rank  ...
0   0.02      0.01     0.01     0.01      Black       7
1   0.01      0.04     0.06     0.01      Death       2
2   0.01      0.01     0.05     0.01      Hardcore    6
3   0.04      0.01     0.01     0.02      Grindcore   1
4   0.02      0.02     0.01     0.02      Deathcore   4
...

高效实现方法

方法1:直接筛选保留列(推荐)

通过构造要保留的列名列表,直接重新生成DataFrame,避免删除操作,效率最高:

FT_index = [1,4,5,7]
# 生成需保留的FT列名
keep_ft = [f'FT{i}' for i in FT_index]
# 筛选所有非FT列
non_ft = [col for col in df.columns if not col.startswith('FT')]
# 合并列并重新赋值
df = df[keep_ft + non_ft]

方法2:批量删除目标FT列

先定位需要删除的FT列,再一次性批量删除:

FT_index = [1,4,5,7]
# 找出所有需删除的FT列
drop_cols = [col for col in df.columns 
             if col.startswith('FT') and int(col[2:]) not in FT_index]
# 批量删除
df.drop(drop_cols, axis=1, inplace=True)

方法3:用filter结合正则筛选

通过正则表达式匹配需保留的列,代码简洁:

FT_index = [1,4,5,7]
# 构造正则:匹配指定FT列 或 非FT列
pattern = '|'.join([f'FT{i}' for i in FT_index]) + '|^(?!FT).*$'
df = df.filter(regex=pattern)

内容的提问来源于stack exchange,提问作者M.Tailleur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:54:19