Hsun-Yi Hsieh Hsun-Yi Hsieh - 4 months ago 10
Python Question

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

Answer

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
Comments