pandas: KeyError:'cannot use a single bool to index into setitem' when dataFrame.loc performs condition judgment

 When using the loc function in pandas dataFrame, as follows

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

 The following error occurred:

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

The reason is that the logic operation is wrong and should be modified into the following form:

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

 

Guess you like

Origin blog.csdn.net/guyu1003/article/details/108536849