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
相关产品推荐
相关产品推荐

