3

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!!

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!!
3

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

2 Comments

Thank you so much. This answer is also correct and elegant.
Cheers, mate! Happy coding to you :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.