Home > Software engineering >  Why does the lookup by index value result in a key error
Why does the lookup by index value result in a key error

Time:12-01

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'

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related