+3 votes
in Programming Languages by (34.9k points)

I have the following pandas dataframe. I want to find average marks and speed per person. How can I apply the "group by" operation to this dataframe?

  Name  Marks  Speed

0    A     90    100

1    B     80    105

2    C     70    105

3    D     55    110

4    A     60     90

5    B     45     60

6    A     60     90

7    C     70    120

1 Answer

+1 vote
by (51.1k points)

The pandas library has groupby() function. You can specify "Name" as an argument to this function and then apply the mean function to compute the average marks and speed per person.

Here is an example:

>>> import pandas as pd
>>> df=pd.DataFrame({'Name': ['A', 'B', 'C', 'D', 'A', 'B', 'A', 'C'], 'Marks':[90,80,70,55,60,45,60,70], 'Speed':[100,105,105,110,90,60,90,120]})
>>> df
  Name  Marks  Speed
0    A     90    100
1    B     80    105
2    C     70    105
3    D     55    110
4    A     60     90
5    B     45     60
6    A     60     90
7    C     70    120

>>> df.groupby(['Name']).mean()
      Marks       Speed
Name                   
A      70.0   93.333333
B      62.5   82.500000
C      70.0  112.500000
D      55.0  110.000000
 


...