cannot use a single bool to index into setitem
Package:
pandas
30911

Exception Class:
KeyError
Raise code
"""
"""
if isinstance(indexer, dict):
# a missing key (but not a tuple indexer)
indexer = indexer["key"]
if isinstance(indexer, bool):
raise KeyError("cannot use a single bool to index into setitem")
return indexer, True
return indexer, False
def convert_from_missing_indexer_tuple(indexer, axes):
""" """
Links to the raise (1)
https://github.com/pandas-dev/pandas/blob/b3e335254f46a526ee3ce9bb757eac4011d9d1fe/pandas/core/indexing.py#L2364Ways to fix
Code to reproduce the exception:
import numpy as np
import pandas as pd
df = pd.DataFrame({'marks':[8, 10, 5, 4, 3, 7]}, index=['student 1', 'student 2', 'student 3', 'student 4', 'student 5', 'student 6'] )
print(df)
# scored_max_marks is a column with yes/no to check if the student scored max marks i.e 10/10
df.loc[str(df['marks']) == '10', 'Scored_max_marks'] = 'Yes' # the boolean expression results in a scaler boolean instead of a series, thus causing the error to occur.
df.loc[str(df['marks']) != '10', 'Scored_max_marks'] = 'No'
print(df)
Working Solution(FIXED):
import numpy as np
import pandas as pd
df = pd.DataFrame({'marks':[8, 10, 5, 4, 3, 7]}, index=['student 1', 'student 2', 'student 3', 'student 4', 'student 5', 'student 6'] )
print(df)
# scored_max_marks is a column with yes/no to check if the student scored max marks i.e 10/10
df.loc[df['marks'] == 10, 'Scored_max_marks'] = 'Yes'
df.loc[df['marks'] != 10, 'Scored_max_marks'] = 'No'
print(df)
Add a possible fix
Please authorize to post fix