0

I have two columns like this.

   name     length
0   Pk      78
2   Pk      59
4   Pk      283
6   Ser     100
7   Ig_2    79
8   Ig_2    77
9   Ser     369

I want to calculate the average of each name. For example

Pk - 140
ser -234.5
Ig_2 -78

How can i do this with python panda.

I was trying this.

df.groupby(level=0).mean()

but didn't work. Is there anyway to use rolling() function for this?

bob
  • 75
  • 1
  • 8

1 Answers1

1
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([['pk', 78], ['pk', 59], ['Ig', 79], ['Ig', 77]], colu
   ...: mns=['name', 'length'])

In [3]: df
Out[3]:
  name  length
0   pk      78
1   pk      59
2   Ig      79
3   Ig      77

In [4]: df.groupby('name').mean()
Out[4]:
      length
name
Ig      78.0
pk      68.5

To sort values in ascending order:

In [11]: df.groupby('name').mean().sort_values(by='length', 
ascending=True)
Out[11]:
      length
name
pk      68.5
Ig      78.0
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22