Pandas dataframe: how to apply describe() to each group and add to new columns?

前端 未结 6 689
执念已碎
执念已碎 2020-12-15 06:20

df:

name score
A      1
A      2
A      3
A      4
A      5
B      2
B      4
B      6 
B      8

Want to get the following new dataframe in

6条回答
  •  心在旅途
    2020-12-15 06:41

    Well I managed to get what you wanted but it doesn't scale very well.

    import pandas as pd
    
    name = ['a','a','a','a','a','b','b','b','b','b']
    score = [1,2,3,4,5,2,4,6,8]
    
    d = pd.DataFrame(zip(name,score), columns=['Name','Score'])
    d = d.groupby('Name').describe()
    d = d.reset_index()
    df2 = pd.DataFrame(zip(d.level_1[8:], list(d.Score)[:8], list(d.Score)[8:]), columns = ['Name','A','B']).T
    
    print df2
    
              0     1         2    3    4    5    6    7
    Name  count  mean       std  min  25%  50%  75%  max
    A         5     3  1.581139    1    2    3    4    5
    B         4     5  2.581989    2  3.5    5  6.5    8
    

提交回复
热议问题