pandas学习-第3章 分组
一、SAC过程
- 内涵
SAC指的是分组操作中的split-apply-combine过程
- split指基于某一些规则,将数据拆成若干组
- apply是指对每一组独立地使用函数
- combine指将每一组的结果组合成某一类数据结构
- apply过程
在该过程中,我们实际往往会遇到四类问题:
- 整合(Aggregation)——即分组计算统计量(如求均值、求每组元素个数)
- 变换(Transformation)——即分组对每个单元的数据进行操作(如元素标准化)
- 过滤(Filtration)——即按照某些规则筛选出一些组(如选出组内某一指标小于50的组)
- 综合问题——即前面提及的三种问题的混合
二、groupby函数
- 分组函数的基本内容:
grouped_single = df.groupby('School')
grouped_single.get_group('S_1').head()
grouped_mul = df.groupby(['School','Class'])
grouped_mul.get_group(('S_2','C_4'))
grouped_single.size()
grouped_mul.size()
grouped_single.ngroups
grouped_mul.ngroups
for name,group in grouped_single:
print(name)
display(group.head())
df.set_index(['Gender','School']).groupby(level=1,axis=0).get_group('S_1').head()
???
- groupby对象的特点
print([attr for attr in dir(grouped_single) if not attr.startswith('_')])
'''
['Address', 'Class', 'Gender', 'Height', 'Math', 'Physics', 'School', 'Weight', 'agg', 'aggregate', 'all', 'any', 'apply', 'backfill', 'bfill', 'boxplot', 'corr', 'corrwith', 'count', 'cov', 'cumcount', 'cummax', 'cummin', 'cumprod', 'cumsum', 'describe', 'diff', 'dtypes', 'expanding', 'ffill', 'fillna', 'filter', 'first', 'get_group', 'groups', 'head', 'hist', 'idxmax', 'idxmin', 'indices', 'last', 'mad', 'max', 'mean', 'median', 'min', 'ndim', 'ngroup', 'ngroups', 'nth', 'nunique', 'ohlc', 'pad', 'pct_change', 'pipe', 'plot', 'prod', 'quantile', 'rank', 'resample', 'rolling', 'sem', 'shift', 'size', 'skew', 'std', 'sum', 'tail', 'take', 'transform', 'tshift', 'var']
'''
grouped_single.head(2)
grouped_single.first()
df.groupby(np.random.choice(['a','b','c'],df.shape[0])).get_group('a').head()
???
df[:5].groupby(lambda x:print(x)).head(0)
df.groupby(lambda x:'奇数行' if not df.index.get_loc(x)%2==1 else '偶数行').groups
'''
{'偶数行': Int64Index([1102, 1104, 1201, 1203, 1205, 1302, 1304, 2101, 2103, 2105, 2202,
2204, 2301, 2303, 2305, 2402, 2404],
dtype='int64', name='ID'),
'奇数行': Int64Index([1101, 1103, 1105, 1202, 1204, 1301, 1303, 1305, 2102, 2104, 2201,
2203, 2205, 2302, 2304, 2401, 2403, 2405],
dtype='int64', name='ID')}
'''
math_score = df.set_index(['Gender','School'])['Math'].sort_index()
grouped_score = df.set_index(['Gender','School']).sort_index().\
groupby(lambda x:(x,'均分及格' if math_score[x].mean()>=60 else '均分不及格'))
for name,_ in grouped_score:print(name)
'''
(('F', 'S_1'), '均分及格')
(('F', 'S_2'), '均分及格')
(('M', 'S_1'), '均分及格')
(('M', 'S_2'), '均分不及格')
'''
df.groupby(['Gender','School'])['Math'].mean()>=60
'''
Gender Scho