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

pandas报错'numpy.bool_' object has no attribute 'isin'解决方法

报错原因

原代码逻辑顺序错误:

  • df["cancelled"].any()会优先执行,返回单个numpy.bool_类型的布尔结果,该类型不存在isin方法,直接触发属性报错。
  • 判断顺序完全颠倒:应该先逐行匹配cancelled列的目标取值,再判断是否存在匹配成功的记录,而非先对整列做真值判断再匹配值。
正确实现方案

调换isin和any()的调用顺序即可实现预期效果:

if df["cancelled"].isin(["Y", "y"]).any():
    print("WARNING - Cancelled offers included!")
else:
    print("OK - No cancelled offers are included.")

代码执行逻辑:

  1. df["cancelled"].isin(["Y", "y"])逐行判断cancelled列取值是否为Y或y,返回和原列等长的布尔序列
  2. .any()判断布尔序列中是否存在任意一个True,存在则说明有已取消的offer,进入警告分支

针对你给出的示例DataFrame,上述代码会正确识别到取值为y的记录,输出对应警告。

兼容扩展写法

如果数据中可能存在大小写混合、带后缀的取消标记(如Y/y/Yes等),可以用统一转小写后匹配的写法避免漏判:

if df["cancelled"].str.lower().str.startswith("y").any():
    print("WARNING - Cancelled offers included!")
else:
    print("OK - No cancelled offers are included.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:57:21