Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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

like image 992
yearntolearn Avatar asked Sep 21 '26 06:09

yearntolearn


1 Answers

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
like image 192
Andy Hayden Avatar answered Sep 23 '26 10:09

Andy Hayden