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

Pandas DataFrame可选条件过滤功能的报错代码修复咨询

Pandas可选条件过滤代码修复

错误原因

  • 你不能在布尔向量的&运算表达式内直接嵌入if语句块,&操作要求两侧均为布尔类型的Series,无返回值的if分支不符合语法要求
  • 原代码中判断lo参数的语句写的是lo ='All',属于赋值操作,不是相等判断,存在语法错误

修复方案

写法1:三元表达式简化版(和原有写法结构接近)

核心逻辑为:对应参数为All时,该位置条件返回True,和其他条件做与运算时不会产生过滤效果,等价于跳过该字段的过滤逻辑。

def filter_for_company(df_source, season, brand, lo):
    mask = (
        (df_source['Production Priority'] == 'Primary')
        & (df_source['Season'] == season)
        & (True if brand == 'All' else df_source['Brand'] == brand)
        & (True if lo == 'All' else df_source['Liaison Office Code'] == lo)             
    )            
    company_df = df_source.loc[mask,:]
    return company_df

写法2:动态构建mask(可读性更高,适合多可选条件场景)

后续需要新增可选过滤条件时,直接新增对应if分支即可,维护成本更低。

def filter_for_company(df_source, season, brand, lo):
    # 先初始化必选过滤条件
    mask = (df_source['Production Priority'] == 'Primary') & (df_source['Season'] == season)
    # 品牌非All时追加品牌过滤条件
    if brand != 'All':
        mask &= df_source['Brand'] == brand
    # 联络处编码非All时追加对应过滤条件
    if lo != 'All':
        mask &= df_source['Liaison Office Code'] == lo
    company_df = df_source.loc[mask,:]
    return company_df

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:18:04