pandas: dataFrame.loc 进行条件判断时出现 KeyError: ‘cannot use a single bool to index into setitem‘

 在使用pandas的dataFrame中的loc函数时,如下

df.loc[('M' in df.Name and df.P>1),'m']=1
df.loc[('M' not in df.Name or df.P < 1), 'm'] = 0

 出现如下错误:

 raise KeyError("cannot use a single bool to index into setitem")
KeyError: 'cannot use a single bool to index into setitem'

原因是,逻辑运算出错,应修改成如下形式:

df.loc[('M' in df.Name) & (df.P>1),'m']=1
df.loc[('M' not in df.Name) | (df.P < 1), 'm'] = 0

猜你喜欢

转载自blog.csdn.net/guyu1003/article/details/108536849