一、SAC过程
SAC指的是分组操作中的split-apply-combine过程。
其中split指基于某一些规则,将数据拆成若干组,apply是指对每一组独立地使用函数,combine指将每一组的结果组合成某一类数据结构。
其中,apply过程有四类问题:
整合(Aggregation)——即分组计算统计量(如求均值、求每组元素个数)
变换(Transformation)——即分组对每个单元的数据进行操作(如元素标准化)
过滤(Filtration)——即按照某些规则筛选出一些组(如选出组内某一指标小于50的组)
综合问题——即前面提及的三种问题的混合
二、groupby函数
使用groupby函数前,需要将其赋给一个变量,然后再对变量进行操作,对其分组。
也可以同时对几列进行分组。
grouped_mul = df.groupby(['School','Class'])
print(grouped_mul.get_group(('S_2','C_4')))
'''
School Class Gender Address Height Weight Math Physics
ID
2401 S_2 C_4 F street_2 192 62 45.3 A
2402 S_2 C_4 M street_7 166 82 48.7 B
2403 S_2 C_4 F street_6 158 60 59.7 B+
2404 S_2 C_4 F street_2 160 84 67.7 B
2405 S_2 C_4 F street_6 193 54 47.6 B
'''
需要注意的是,在对多列进行分组的时候,赋值给变量的操作,需要用中括号[]
将列的名称括起来。而调用函数的时候,需要用括号()
将内容括起。
grouped_single.size()
grouped_mul.size()
grouped_single.ngroups
grouped_mul.ngroups
使用上述4个函数,可以统计其中的容量和组数。
level参数(用于多级索引)和axis参数
grouped_mul = df.groupby(['School','Class'])
print(df.set_index(['Gender','School']).groupby(level=0,axis=0).get_group('M').head())
'''
Class Address Height Weight Math Physics
Gender School
M S_1 C_1 street_1 173 63 34.0 A+
S_1 C_1 street_2 186 82 87.2 B+
S_1 C_2 street_5 188 68 97.0 A-
S_1 C_2 street_6 160 53 58.8 A+
S_1 C_3 street_4 161 68 31.5 B+
'''
三、问题和习题
问题
1、什么是fillna的前向/后向填充,如何实现?
答:
#向前和向后填充,使用 ffill和 bfill
fillna(method='ffill')
fillna(method='bfill')
2、下面的代码实现了什么功能?请仿照设计一个它的groupby版本。
s = pd.Series ([0, 1, 1, 0, 1, 1, 1, 0])
s1 = s.cumsum()
result = s.mul(s1).diff().where(lambda x: x < 0).ffill().add(s1,fill_value =0)
答:
s = pd.Series ([0, 1, 1, 0, 1, 1, 1, 0])
s1 = s.cumsum()
print(s1) #累计求和[0,1,2,2,3,4,5,5]
result = s.mul(s1).diff().where(lambda x: x < 0).ffill().add(s1,fill_value =0)
print(result) #进行差分操作
3、如何计算组内0.25分位数与0.75分位数?要求显示在同一张表上。
答:
def R1(x):
return np.percentile(x,25)
def R2(x):
return np.percentile(x,75)
print(grouped_single.agg(percentile_25=pd.NamedAgg(column='Math',aggfunc=R1),percentile_75=pd.NamedAgg(column='Math', aggfunc=R2)))
4、既然索引已经能够选出某些符合条件的子集,那么filter函数的设计有什么意义?
答:根据要求过滤出更大的整体子集。
5、整合、变换、过滤三者在输入输出和功能上有何异同?
答:
整合:即分组计算统计量。
变换:即分组对每个单元的数据进行操作。
过滤:即按照某些规则筛选出一些组。
6、在带参数的多函数聚合时,有办法能够绕过wrap技巧实现同样功能吗?
答:
2.习题
1、现有一份关于diamonds的数据集,列分别记录了克拉数、颜色、开采深度、价格,请解决下列问题:
(a) 在所有重量超过1克拉的钻石中,价格的极差是多少?
df = pd.read_csv('Diamonds.csv')
print(df.head())
df_r = df.query('carat>1')['price']
print(df_r.max()-df_r.min())
'''
carat color depth price
0 0.23 E 61.5 326
1 0.21 E 59.8 326
2 0.23 E 56.9 327
3 0.29 I 62.4 334
4 0.31 J 63.3 335
17561
'''