一、groupby函数
(a)根据某一列分组
grouped_single = df.groupby('School')
groupby分组后会生成一个groupby对象,该对象不会返回任何东西,只有当相应方法被调用才会起作用
比如取出一个组
grouped_single.get_group('S_1')
(b)根据某几列分组
grouped_single= df.groupby(['School','Class'])
grouped_single.get_group(('S_2','C_4'))
(c)获取组容量与组数
grouped_single.size() #输出每个组的组名和容量
grouped_single.ngroups #输出组的数量
(d)组的遍历
for name,group in group_single:
print(name)
display(group.head(3))
(e)level参数(多级索引)和axis参数
df.set_index(['Gender','School']).groupby(level=1,axis=0).get_group('S_1')
2.group对象的特点
(a)查看可调用的方法
dir()函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数返回参数的属性、方法列表
print([attr for attr in dir(grouped_single) if not attr.startswith('_')])
(b)分组依据
根据奇偶行分组
df.groupby(lambda x:'奇数行' if not df.index.get_loc(x)%2==1 else '偶数行').groups
(c)groupby的[]操作
df.groupby(['Gender','School'])['Math'].mean()>=60
df.groupby(['Gender','School'])[['Math','Height']].mean()
#可以筛选男性学校1的数学平均分
(e)连续型变量分组
bins = [0,40,60,80,90,100]
cuts = pd.cut(df['Math'],bins=bins) #可选label添加自定义标签
df.groupby(cuts)['Math'].count()
二、聚合、过滤和变换
1.聚合
聚合就是把一堆数,变成一个标量,因此mean/sum/size/count/std/var/sem/describe/first/last/nth/min/max都是聚合函数
(a)同时使用多个聚合函数
group_m.agg(['sum','mean','std'])
#group_m是根据学校分组后取出math一列
group_m.agg([('rename_sum','sum'),('rename_mean','mean')])#利用元组进行命名,本来名字是sum,把sum改成rename_sum
grouped_mul.agg({'Math':['mean','max'],'Height':'var'})#对math列求均值最大值
(b)使用自定义函数
grouped_single['Math'].agg(lambda x:print(x.head(),'间隔'))
#可以发现,agg函数的传入是分组逐列进行的,有了这个特性就可以做许多事情
2.过滤组(筛选组)
filter函数是用来筛选某些组的(务必记住结果是组的全体),因此传入的值应当是布尔标量
grouped_single[['Math','Physics']].filter(lambda x:(x['Math']>32).all()).head()
#就是需要组里的每个math都大于32
3.变换
transform函数传入的对象是组内的列
grouped_single[['Math','Height']].transform(lambda x:x-x.min()).head()
同理可对组内值进行标准化,缺失值填充
三、apply函数
1.灵活性,可返回数值、列表、数据框
(1)df[['School','Math','Height']].groupby('School').apply(lambda x:x.max())
(2)返回数据框
df[['School','Math','Height']].groupby('School')\
.apply(lambda x:pd.DataFrame({'col1':x['Math']-x['Math'].max(),
'col2':x['Math']-x['Math'].min(),
'col3':x['Height']-x['Height'].max(),
'col4':x['Height']-x['Height'].min()})).head()
2.用apply同时统计多个指标
可以借助OrderedDict工具进行快捷的统计
from collections import OrderedDict
def f(df):
data = OrderedDict()
data['M_sum'] = df['Math'].sum()
data['W_var'] = df['Weight'].var()
data['H_mean'] = df['Height'].mean()
return pd.Series(data)
grouped_single.apply(f)