nicomp
nicomp

Reputation: 4647

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

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'

Upvotes: 0

Views: 60

Answers (3)

timgeb
timgeb

Reputation: 78680

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

Upvotes: 2

Sam
Sam

Reputation: 731

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.

Upvotes: 0

cavalcantelucas
cavalcantelucas

Reputation: 1382

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.

Upvotes: 0

Related Questions