votes up 4

cannot use a single bool to index into setitem

Package:
pandas
github stars 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):
    """ """

Ways to fix

votes up 1 votes down

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)
Jun 13, 2021 umangtaneja98 answer

Add a possible fix

Please authorize to post fix