https://github.com/yeayee/joyful-pandas/blob/master/第3章%20分组.ipynb聚合(Aggregation)
聚合(Aggregation)
(a)常用聚合函数
所谓聚合就是把一个数列,变成一个标量,因此mean/sum/size/count/std/var/sem/describe/first/last/nth/min/max都是聚合函数
group_m = grouped_single['Math']
group_m.std().values/np.sqrt(group_m.count().values)== group_m.sem().values
Out[21]:
array([ True, True])
标准误差函数
(b)同时使用多个聚合函数
group_m.agg(['sum','mean','std'])
Out[22]:
sum mean std
School
S_1 956.2 63.746667 23.077474
S_2 1191.1 59.555000 17.589305
利用元组进行重命名
In [23]:
group_m.agg([('rename_sum','sum'),('rename_mean','mean')])
Out[23]:
rename_sum rename_mean
School
S_1 956.2 63.746667
S_2 1191.1 59.555000
指定哪些函数作用哪些列
In [24]:
grouped_mul.agg({'Math':['mean','max'],'Height':'var'})
Out[24]:
Math Height
mean max var
School Class
S_1 C_1 63.78 87.2 183.3
C_2 64.30 97.0 132.8
C_3 63.16 87.7 179.2
S_2 C_1 58.56 83.3 54.7
C_2 62.80 85.4 256.0
C_3 63.06 95.5 205.7
C_4 53.80 67.7 300.2
(c)使用自定义函数
In [25]:
grouped_single['Math'].agg(lambda x:print(x.head(),'间隔'))
#可以发现,agg函数的传入是分组逐列进行的,有了这个特性就可以做许多事情
1101 34.0
1102 32.5
1103 87.2
1104 80.4
1105 84.8
Name: Math, dtype: float64 间隔
2101 83.3
2102 50.6
2103 52.5
2104 72.2
2105 34.2
Name: Math, dtype: float64 间隔
Out[25]:
School
S_1 None
S_2 None
Name: Math, dtype: object
官方没有提供极差计算的函数,但通过agg可以容易地实现组内极差计算
In [26]:
grouped_single['Math'].agg(lambda x:x.max()-x.min())
Out[26]:
School
S_1 65.5
S_2 62.8
Name: Math, dtype: float64
https://blog.csdn.net/qq_16234613/article/details/78245325
http://sofasofa.io/forum_main_post.php?postid=1002654