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

pandas使用loc查询出现KeyError:Boolean标签需配合布尔索引使用

报错原因解析
  • 错误根源:你用is None来判断pandas Series中的空值,这是完全错误的用法。
    • customer.referee_id是一个Series对象,is None的作用是判断整个Series对象本身是否为None,而不是逐个检查Series里的元素是否为空。这里这个Series显然是存在的,所以整个表达式返回单个布尔值False。
  • 为什么会触发KeyError:df.loc[]要求布尔索引必须是和DataFrame行数匹配的布尔数组,但你传入的是单个False。pandas会把这个单个布尔值当成要查找的行标签,找不到对应标签时就抛出KeyError: 'False: boolean label can not be used without a boolean index'。

正确写法

要判断Series中的空值,应该用pandas提供的isna()或isnull()方法:

def find_customer_referee(customer: pd.DataFrame) -> pd.DataFrame:
    return customer.loc[customer.referee_id.isna(), ['name']]

或者:

def find_customer_referee(customer: pd.DataFrame) -> pd.DataFrame:
    return customer.loc[customer.referee_id.isnull(), ['name']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:07:09