You need to enable JavaScript to run this app. Pandas DataFrame中product_description含manufacturer列值如何删除对应行
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame中product_description含manufacturer列值如何删除对应行

报错根因

之前使用的df[~df.product_description.str.contains(df.manufacturer)]触发报错的核心原因是:Series.str.contains方法原生设计是接收单个字符串或正则表达式作为匹配规则,当直接把另一列的Series对象(即df.manufacturer)传入匹配参数时,方法内部会尝试将传入对象转为可哈希的匹配模式,而Series作为可变对象无法完成哈希处理,最终触发指定的TypeError。

可行实现方案

逐行匹配过滤逻辑

  • 方案1:利用apply逐行生成过滤掩码
    逐行读取两个列的文本内容做包含判断,构造过滤规则,代码可跨Pandas所有稳定版本运行:
    # 生成保留行的掩码:返回True代表该行需要保留(即product_description不含对应manufacturer内容)
    keep_mask = df.apply(
        lambda row: str(row['manufacturer']) not in str(row['product_description']),
        axis=1
    )
    # 应用掩码完成过滤
    filtered_df = df[keep_mask].reset_index(drop=True)
    
    代码中用str()包裹取值的作用是兼容空值、非字符串类型的列内容,避免因为None、数值型数据触发匹配报错。
  • 方案2:列表推导式生成掩码(大数据量下性能更优)
    相比apply的逐行遍历开销,列表推导式直接遍历两列的取值生成判断结果,在万行以上规模的数据集上运行速度会有明显提升:
    # 逐行判断是否保留
    keep_row_flag = [
        str(mfr) not in str(desc)
        for desc, mfr in zip(df['product_description'], df['manufacturer'])
    ]
    filtered_df = df[keep_row_flag].reset_index(drop=True)
    

小提示:如果需要忽略文本大小写匹配(比如manufacturer是"Apple",product_description里是"apple"也算匹配条件),可以在判断前把两个值都转为小写再加判断,调整判断逻辑为str(row['manufacturer']).lower() not in str(row['product_description']).lower()即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 09:54:08