yearntolearn
yearntolearn

Reputation: 1074

Query based on index value or value in a column in python

I have a pandas data frame from which I computed the mean scores of students. Student scores are stored in data as below:

   name score
 0 John   90
 1 Mary   87
 2 John  100
 3 Suzie  90
 4 Mary   88

By using meanscore = data.groupby("name").mean() I obtain score name John 95 Mary 87.5 Suzie 90

I would like to query, for instance, meanscore['score'][meanscore['name'] == 'John'] This line yields KeyError: 'name'

I know my way of doing it is not nice, as I can actually find out the meanscore of John by using mean['score'][0].

My question is: is there a way to find the corresponding index value of each name (e.g. [0] for John, [1] for Mary and [2] for Suzie) in my query? Thank you!!

Upvotes: 3

Views: 379

Answers (2)

Andy Hayden
Andy Hayden

Reputation: 375605

You can use loc:

In [11]: meanscore
Out[11]:
       score
name
John    95.0
Mary    87.5
Suzie   90.0

In [12]: meanscore.loc["John", "score"]
Out[12]: 95.0

Upvotes: 4

mechanical_meat
mechanical_meat

Reputation: 169384

You can do:

meanscore['score']['John']

Example:

>>> df
    name  score
0   John     90
1   Mary     87
2   John    100
3  Suzie     90
4   Mary     88

>>> meanscore = df.groupby('name').mean()
>>> meanscore
       score
name
John    95.0
Mary    87.5
Suzie   90.0
>>> meanscore['score']['John']
95.0

Upvotes: 3

Related Questions