Home > database >  Pandas: Return the average of a specific category
Pandas: Return the average of a specific category

Time:02-16

I have this Survey Data df, and the School_Grade is categorical.

Name       School_Grade       Math_Score
Ana         7th Grade              95
Dylan       6th Grade              84
Syriad      5th Grade              83
Stacy       4th Grade              79
Chris       6th Grade              88
Winnie      7th Grade              85
Travis      4th Grade              90
Brady       5th Grade              92

How can I return the average score for each grade level?

I can solve the problem with this:

df_7th_grade = df[df['School_Grade'] == '7th Grade']
print(df_7th_grade['Math_Score'].mean())

The problem with the solution above is that it is tedious solution if you have many categories.

How can I code it so that the mean would be iterated for all the School_Grade?

CodePudding user response:

You can do groupby

out = df.groupby('School_Grade')['Math_Score'].mean()

Result can be assess with

out.loc['7th Grade']
  • Related