Why does the lookup by index value result in a key error

Question:

The code:

df = pd.DataFrame({
    'MNumber':['M03400001','M00000021','M10450001','M00003420','M02635915','M51323275','M63061229','M63151022'],
    'GPA':[3.01, 4.00, 2.95, 2.90, 3.50, 3.33, 2.99, 3.98],
    'major':['IS','BANA','IS','IS','IS','BANA','IS', 'BANA'],
    'internship':['P&G', 'IBM', 'P&G', 'IBM', 'P&G', 'EY','EY', 'Great American'],
    'job_offers':[2,0,0,3,2,1,4,3],
    'graduate_credits':[5,1,0,5,2,2,3,4]
})
x  =  df.groupby('internship').describe()
#print(x.info())
print(x["IBM"])

The error:

KeyError: 'IBM'
Asked By: nicomp

||

Answers:

Your dataframe x does not contain a key called IBM.

Try

print(x)

To see the keys contained in your dataframe.
Even better, you can try

print(x.columns)

To see the available columns of your dataframe.

Answered By: cavalcantelucas

x['IBM'] tries to access the column 'IBM', which does not exist.
x.loc['IBM'] accesses the row 'IBM', which does exist.

Answered By: timgeb

Pandas DataFrame groupby when used, it changes the column specified to index of the DataFrame. So, you should try to index the row rather than the column as stated by @timgeb.

Answered By: Sam
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.