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

使用apply+Lambda筛选DataFrame含指定关键词且排除Total列问题排查

问题:筛选含budget但排除total的DataFrame列时出错

需求

筛选DataFrame中包含关键词budget的列,同时排除包含"total"的列。

目标DataFrame

Section Budget      Hours   Budget  Hours       Total Budget
1       70460.04    702.08  0       0           81581.02
2       137149.03   1141.3  0       0           159823.28
3       33958.35    227.05  0       0           55243.23
4       160688.52   1062    0       0           176156.52
5       1340843.5   12311.65 0       0           1367133.42
6       73295.25    480     0       0           73295.25
7       0           0       0       0           0
8       1131911.04  6537.96 0       0           1131911.04
9       2216733.4   16425.64 0       0           3708886.3

当前代码

keyword = budget
row, col = np.where((headers_df.apply(lambda x: x.astype(str).str.contains(keyword, case=False)))
                    & (~headers_df.apply(lambda x: x.astype(str).str.contains('total', case=False))))

输出情况

  • 当前col结果:(1, 3, 5)
  • 期望col结果:(1, 3)

问题原因与修复

  1. keyword未定义为字符串:keyword = budget会被Python识别为变量,而非字符串"budget",必须改为keyword = "budget"。
  2. 冗余的apply调用:你要筛选的是列,直接操作DataFrame的列名更高效,无需遍历每行数据判断列名。

修复后的代码(推荐写法)

# 生成列名的筛选掩码
mask = (df.columns.str.contains('budget', case=False)) & (~df.columns.str.contains('total', case=False))
# 获取符合条件的列索引
col = np.where(mask)[0]

若坚持使用apply的写法

keyword = "budget"
mask = (headers_df.apply(lambda x: keyword.lower() in str(x).lower())) & (~headers_df.apply(lambda x: 'total' in str(x).lower()))
row, col = np.where(mask)

这样就能得到期望的col = (1, 3)结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 01:45:41