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

pandas如何基于多个条件批量筛选数据集指定列

问题原因

你的代码中存在两处可优化/错误点:

  • str.contains('gibberish','tech')写法不符合pandas语法:Series.str.contains()的第二个参数不是第二个匹配字符串,而是大小写控制、正则开关等配置参数,因此该语句仅过滤了包含gibberish的列,未过滤tech列
  • endswith方法原生支持传入多后缀元组,无需拆分写多段过滤逻辑,可简化代码

正确代码

针对上百个变量的维护需求,推荐将过滤规则拆分归类,后续新增过滤规则直接修改对应列表/元组即可:

import pandas as pd

# 定义排除规则,后续新增规则直接修改对应位置即可
exclude_suffix = ('_pct', '_ln')
exclude_cols = ['gibberish', 'tech']

df_selected = my_df.loc[:,
    ~my_df.columns.str.endswith(exclude_suffix) &
    ~my_df.columns.isin(exclude_cols)
]

输出结果

运行上述代码后得到预期结果:

idtypesalessales_roiflag
1corp345670.100
2smb21900.211
3smb18700.220
4corp220000.151
5mid100000.161

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:36:03