Q. Consider the following code


Section = ['A', 'B', 'C']
Classes = [ 6, 4, 3]
dc = {'Section':Section, 'No. of Classes': Classes}
clasDf = pd.DataFrame (dc, index = ['True', 'False', 'True'])
print (clasdf.loc [True])

(i) Why is it giving KeyError if you run the given code?

(ii) Suggest the correction /solution for the above problem.


Answer :-

(i) The above code is giving KeyError because it has created the dataframe with string indexes (values 'True' and 'False' are enclosed in quotes) and it is trying to access rows considering the indexes as Boolean.

(ii) The solution for the above problem is to remove the quotes from the indexes while creating the dataframe, i.e., 4th line of the code should be changed to :



clasDf = pd.DataFrame (dc, index = [True, False, True] )

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post