數(shù)據(jù)分析之Pandas分組操作總結(jié)
↑↑↑關(guān)注后"星標(biāo)"Datawhale
每日干貨 &?每月組隊(duì)學(xué)習(xí),不錯(cuò)過(guò)
?Datawhale干貨?作者:耿遠(yuǎn)昊,Datawhale成員
Pandas做分析數(shù)據(jù),可以分為索引、分組、變形及合并四種操作。之前介紹過(guò)索引操作,現(xiàn)在接著對(duì)Pandas中的分組操作進(jìn)行介紹:主要包含SAC含義、groupby函數(shù)、聚合、過(guò)濾和變換、apply函數(shù)。文章的最后,根據(jù)今天的知識(shí)介紹,給出了6個(gè)問(wèn)題與2個(gè)練習(xí),供大家學(xué)習(xí)實(shí)踐。

在詳細(xì)講解每個(gè)模塊之前,首先讀入數(shù)據(jù):
import?numpy?as?npimport pandas as pddf = pd.read_csv('data/table.csv',index_col='ID')df.head()

SAC過(guò)程
1. 內(nèi)涵
SAC指的是分組操作中的split-apply-combine過(guò)程。其中split指基于某一些規(guī)則,將數(shù)據(jù)拆成若干組;apply是指對(duì)每一組獨(dú)立地使用函數(shù);combine指將每一組的結(jié)果組合成某一類數(shù)據(jù)結(jié)構(gòu)。
2. apply過(guò)程
在apply過(guò)程中,我們實(shí)際往往會(huì)遇到四類問(wèn)題:
整合(Aggregation):即分組計(jì)算統(tǒng)計(jì)量(如求均值、求每組元素個(gè)數(shù));
變換(Transformation):即分組對(duì)每個(gè)單元的數(shù)據(jù)進(jìn)行操作(如元素標(biāo)準(zhǔn)化);
過(guò)濾(Filtration):即按照某些規(guī)則篩選出一些組(如選出組內(nèi)某一指標(biāo)小于50的組);
綜合問(wèn)題:即前面提及的三種問(wèn)題的混合。
groupby函數(shù)
經(jīng)過(guò)groupby后會(huì)生成一個(gè)groupby對(duì)象,該對(duì)象本身不會(huì)返回任何內(nèi)容,只有當(dāng)相應(yīng)的方法被調(diào)用才會(huì)起作用。
1. 分組函數(shù)的基本內(nèi)容:
根據(jù)某一列分組
根據(jù)某幾列分組
組容量與組數(shù)
組的遍歷
level參數(shù)(用于多級(jí)索引)和axis參數(shù)
a). 根據(jù)某一列分組
grouped_single = df.groupby('School')經(jīng)過(guò)groupby后會(huì)生成一個(gè)groupby對(duì)象,該對(duì)象本身不會(huì)返回任何東西,只有當(dāng)相應(yīng)的方法被調(diào)用才會(huì)起作用。例如取出某一個(gè)組:
grouped_single.get_group('S_1').head()
b). 根據(jù)某幾列分組
grouped_mul = df.groupby(['School','Class'])grouped_mul.get_group(('S_2','C_4'))

c). 組容量與組數(shù)
調(diào)用的時(shí)候最好先根據(jù)size看下里面的內(nèi)容,不然在get_group的時(shí)候可能會(huì)出錯(cuò)。
grouped_single.size()
grouped_mul.size()
grouped_single.ngroupsgrouped_mul.ngroups

d). 組的遍歷
for name,group in grouped_single:print(name)display(group.head())

e). level參數(shù)(用于多級(jí)索引)和axis參數(shù)
df.set_index(['Gender','School']).groupby(level=1,axis=0).get_group('S_1').head()
查看所有可調(diào)用的方法
分組對(duì)象的head 和first
分組依據(jù)
groupby的[]操作
- 連續(xù)型變量分組
a). 查看所有可調(diào)用的方法
由此可見(jiàn),groupby對(duì)象可以使用相當(dāng)多的函數(shù),靈活程度很高
print([attr for attr in dir(grouped_single) if not attr.startswith('_')])
b). 分組對(duì)象的head和first
對(duì)分組對(duì)象使用head函數(shù),返回的是每個(gè)組的前幾行,而不是數(shù)據(jù)集前幾行
grouped_single.head(2)
first顯示的是以分組為索引的每組的第一個(gè)分組信息
grouped_single.first()
c). 分組依據(jù)
對(duì)于groupby函數(shù)而言,分組的依據(jù)是非常自由的,只要是與數(shù)據(jù)框長(zhǎng)度相同的列表即可,同時(shí)支持函數(shù)型分組。
df.groupby(np.random.choice(['a','b','c'],df.shape[0])).get_group('a').head()# 相當(dāng)于將np.random.choice(['a','b','c'],df.shape[0])當(dāng)做新的一列進(jìn)行分組

從原理上說(shuō),我們可以看到利用函數(shù)時(shí),傳入的對(duì)象就是索引,因此根據(jù)這一特性可以做一些復(fù)雜的操作。
df[:5].groupby(lambda x:print(x)).head(0)
根據(jù)奇偶行分組。
df.groupby(lambda x:'奇數(shù)行' if not df.index.get_loc(x)%2==1 else '偶數(shù)行').groups
如果是多層索引,那么lambda表達(dá)式中的輸入就是元組,下面實(shí)現(xiàn)的功能為查看兩所學(xué)校中男女生分別均分是否及格。注意:此處只是演示groupby的用法,實(shí)際操作不會(huì)這樣寫(xiě)。
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)

d). groupby的[]操作
可以用[]選出groupby對(duì)象的某個(gè)或者某幾個(gè)列,上面的均分比較可以如下簡(jiǎn)潔地寫(xiě)出:
df.groupby(['Gender','School'])['Math'].mean()>=60
用列表可選出多個(gè)屬性列:
df.groupby(['Gender','School'])[['Math','Height']].mean()
e). 連續(xù)型變量分組
例如利用cut函數(shù)對(duì)數(shù)學(xué)成績(jī)分組:
bins = [0,40,60,80,90,100]cuts = pd.cut(df['Math'],bins=bins) #可選label添加自定義標(biāo)簽df.groupby(cuts)['Math'].count()

聚合、過(guò)濾和變換
1. 聚合
常用聚合函數(shù)
同時(shí)使用多個(gè)聚合函數(shù)
使用自定義函數(shù)
利用NameAgg函數(shù)
帶參數(shù)的聚合函數(shù)
a). 常用聚合函數(shù)
所謂聚合就是把一堆數(shù),變成一個(gè)標(biāo)量,因此mean/sum/size/count/std/var/sem/describe/first/last/nth/min/max都是聚合函數(shù)。為了熟悉操作,不妨驗(yàn)證標(biāo)準(zhǔn)誤sem函數(shù),它的計(jì)算公式是:組內(nèi)標(biāo)準(zhǔn)差/組容量,下面進(jìn)行驗(yàn)證:
group_m?=?grouped_single['Math']group_m.std().values/np.sqrt(group_m.count().values)== group_m.sem().values
![]()
b). 同時(shí)使用多個(gè)聚合函數(shù)
group_m.agg(['sum','mean','std'])
利用元組進(jìn)行重命名
group_m.agg([('rename_sum','sum'),('rename_mean','mean')])
指定哪些函數(shù)作用哪些列
grouped_mul.agg({'Math':['mean','max'],'Height':'var'})
c). 使用自定義函數(shù)
grouped_single['Math'].agg(lambda x:print(x.head(),'間隔'))#可以發(fā)現(xiàn),agg函數(shù)的傳入是分組逐列進(jìn)行的,有了這個(gè)特性就可以做許多事情

官方?jīng)]有提供極差計(jì)算的函數(shù),但通過(guò)agg可以容易地實(shí)現(xiàn)組內(nèi)極差計(jì)算
grouped_single['Math'].agg(lambda x:x.max()-x.min())
d). 利用NamedAgg函數(shù)進(jìn)行多個(gè)聚合
注意:不支持lambda函數(shù),但是可以使用外置的def函數(shù)
def R1(x):return x.max()-x.min()def R2(x):return x.max()-x.median()grouped_single['Math'].agg(min_score1=pd.NamedAgg(column='col1', aggfunc=R1),max_score1=pd.NamedAgg(column='col2', aggfunc='max'),range_score2=pd.NamedAgg(column='col3', aggfunc=R2)).head()

e). 帶參數(shù)的聚合函數(shù)
判斷是否組內(nèi)數(shù)學(xué)分?jǐn)?shù)至少有一個(gè)值在50-52之間:
def f(s,low,high):return s.between(low,high).max()grouped_single['Math'].agg(f,50,52)
如果需要使用多個(gè)函數(shù),并且其中至少有一個(gè)帶參數(shù),則使用wrap技巧:
def f_test(s,low,high):return s.between(low,high).max()def agg_f(f_mul,name,*args,**kwargs):def wrapper(x):return f_mul(x,*args,**kwargs)wrapper.__name__ = namereturn wrappernew_f = agg_f(f_test,'at_least_one_in_50_52',50,52)grouped_single['Math'].agg([new_f,'mean']).head()

filter函數(shù)是用來(lái)篩選某些組的(務(wù)必記住結(jié)果是組的全體),因此傳入的值應(yīng)當(dāng)是布爾標(biāo)量。
grouped_single[['Math','Physics']].filter(lambda?x:(x['Math']>32).all()).head()
傳入對(duì)象
利用變換方法進(jìn)行組內(nèi)標(biāo)準(zhǔn)化
利用變換方法進(jìn)行組內(nèi)缺失值的均值填充
a). 傳入對(duì)象
transform函數(shù)中傳入的對(duì)象是組內(nèi)的列,并且返回值需要與列長(zhǎng)完全一致
grouped_single[['Math','Height']].transform(lambda x:x-x.min()).head()
如果返回了標(biāo)量值,那么組內(nèi)的所有元素會(huì)被廣播為這個(gè)值
grouped_single[['Math','Height']].transform(lambda x:x.mean()).head()
b). 利用變換方法進(jìn)行組內(nèi)標(biāo)準(zhǔn)化
grouped_single[['Math','Height']].transform(lambda x:(x-x.mean())/x.std()).head()
c). 利用變換方法進(jìn)行組內(nèi)缺失值的均值填充
df_nan = df[['Math','School']].copy().reset_index()df_nan.loc[np.random.randint(0,df.shape[0],25),['Math']]=np.nandf_nan.head()

df_nan.groupby('School').transform(lambda x: x.fillna(x.mean())).join(df.reset_index()['School']).head()
apply函數(shù)
1. apply函數(shù)的靈活性標(biāo)量返回值
列表返回值
數(shù)據(jù)框返回值
可能在所有的分組函數(shù)中,apply是應(yīng)用最為廣泛的,這得益于它的靈活性:對(duì)于傳入值而言,從下面的打印內(nèi)容可以看到是以分組的表傳入apply中。
df.groupby('School').apply(lambda x:print(x.head(1)))
apply函數(shù)的靈活性很大程度來(lái)源于其返回值的多樣性:
a). 標(biāo)量返回值
df[['School','Math','Height']].groupby('School').apply(lambda?x:x.max())
df[['School','Math','Height']].groupby('School').apply(lambda x:x-x.min()).head()
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同時(shí)統(tǒng)計(jì)多個(gè)指標(biāo)
此處可以借助OrderedDict工具進(jìn)行快捷的統(tǒng)計(jì):
from collections import OrderedDictdef 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)

問(wèn)題與練習(xí)
問(wèn)題
import numpy as npimport pandas as pddf = pd.read_csv('data/table.csv',index_col='ID')df.head(3)
df_nan = df[['Math','School']].copy().reset_index()df_nan.loc[np.random.randint(0,df.shape[0],25),['Math']]=np.nandf_nan.head()
fillna 的method方法可以控制參數(shù)的填充方式,是向上填充:將缺失值填充為該列中它上一個(gè)未缺失值;向下填充相反
method : {‘backfill', ‘bfill', ‘pad', ‘ffill', None}, default None
pad / ffill: 向下自動(dòng)填充
backfill / bfill: 向上自動(dòng)填充
df_nan.Math=df_nan.Math.fillna(method='pad')df_nan.head()
問(wèn)題2. 下面的代碼實(shí)現(xiàn)了什么功能?請(qǐng)仿照設(shè)計(jì)一個(gè)它的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)
s1:將s序列求累加和 [0, 1, 2, 2, 3, 4, 5, 5]
s.mul(s1):s 與s1累乘 [0, 1, 2, 0, 3, 4, 5, 0]
.diff() 求一階差分 [nan, 1.0, 1.0, -2.0, 3.0, 1.0, 1.0, -5.0]
.where(lambda x: x < 0) 值是否小于0:[nan, nan, nan, -2.0, nan, nan, nan, -5.0]
.ffill():向下填充 [nan, nan, nan, -2.0, -2.0, -2.0, -2.0, -5.0]
.add(s1,fill_value =0) 缺失值補(bǔ)0后與s1求和:[0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 3.0, 0.0]
list(s.mul(s1).diff().where(lambda x: x < 0).ffill().add(s1,fill_value =0))gp =df.groupby('School')gp.apply(lambda x:x['Math'].mul(x['Math'].cumsum()).diff().where(lambda m: m < 0).ffill().add(x['Math'].cumsum(),fill_value =0)
問(wèn)題3. 如何計(jì)算組內(nèi)0.25分位數(shù)與0.75分位數(shù)?要求顯示在同一張表上。
問(wèn)題4. 既然索引已經(jīng)能夠選出某些符合條件的子集,那么filter函數(shù)的設(shè)計(jì)有什么意義?答:filter函數(shù)是用來(lái)篩選組的,結(jié)果是組的全體。問(wèn)題5. 整合、變換、過(guò)濾三者在輸入輸出和功能上有何異同?gp.apply(lambda x:pd.DataFrame({'q25':x.quantile(0.25),'q75':x.quantile(0.75)}))
整合(Aggregation)分組計(jì)算統(tǒng)計(jì)量:輸入的是每組數(shù)據(jù),輸出是每組的統(tǒng)計(jì)量,在列維度上是標(biāo)量。
變換(Transformation):即分組對(duì)每個(gè)單元的數(shù)據(jù)進(jìn)行操作(如元素標(biāo)準(zhǔn)化):輸入的是每組數(shù)據(jù),輸出是每組數(shù)據(jù)經(jīng)過(guò)某種規(guī)則變換后的數(shù)據(jù),不改變數(shù)據(jù)的維度。
- 過(guò)濾(Filtration):即按照某些規(guī)則篩選出一些組:輸入的是每組數(shù)據(jù),輸出的是滿足要求的組的所有數(shù)據(jù)。
問(wèn)題6. 在帶參數(shù)的多函數(shù)聚合時(shí),有辦法能夠繞過(guò)wrap技巧實(shí)現(xiàn)同樣功能嗎?
def f_test(s,low=50,high=52):return s.between(low,high).max()grouped_single['Math'].agg([f_test,'mean']).head()#這里需要理解的是,agg除了傳入字符形式的np函數(shù)外,其他傳入對(duì)象也應(yīng)當(dāng)是一個(gè)函數(shù)

練習(xí)
練習(xí)1 :現(xiàn)有一份關(guān)于diamonds的數(shù)據(jù)集,列分別記錄了克拉數(shù)、顏色、開(kāi)采深度、價(jià)格,請(qǐng)解決下列問(wèn)題:
df=pd.read_csv('data/Diamonds.csv')df.head(3)
(a).?在所有重量超過(guò)1克拉的鉆石中,價(jià)格的極差是多少?
df.groupby(lambda?x?:?'>1克拉'?if?df.loc[x,'carat']>1.0?else?'<=1克拉').price.agg(lambda?x:x.max()-x.min()(b). 若以開(kāi)采深度的0.2\0.4\0.6\0.8分位數(shù)為分組依據(jù),每一組中鉆石顏色最多的是哪一種?該種顏色是組內(nèi)平均而言單位重量最貴的嗎?
bins=[df.depth.quantile(i) for i in [0,0.2,0.4,0.6,0.8,1]]df['cuts']=pd.cut(df.depth,bins=bins)df['unit_price']=df['price']/df['carat']df.groupby(['cuts','color'])['unit_price'].agg(['count','mean']).reset_index().groupby('cuts')\.apply(lambda x:pd.DataFrame({'cuts':x['cuts'],'color':x['color'],'count':x['count'],'count_diff':x['count']-x['count'].max(), 'mean':x['mean'], 'mean_diff':x['mean']-x['mean'].max()})).sort_values(by='count_diff',ascending=False)##有些是單位質(zhì)量最貴的,有些不是(當(dāng)count_diff與mean_diff同為0時(shí),則是)
(c). 以重量分組(0-0.5,0.5-1,1-1.5,1.5-2,2+),按遞增的深度為索引排序,求每組中連續(xù)的嚴(yán)格遞增價(jià)格序列長(zhǎng)度的最大值。
bins=[0,0.5,1,1.5,2,6]df['carat_cuts']=pd.cut(df.carat,bins=bins)sorted_df=df.groupby('carat_cuts').apply(lambda x:x.sort_values('depth')).reset_index(drop=True)#再求價(jià)格遞增tp=sorted_df.groupby('carat_cuts').apply(lambda x: pd.DataFrame({'carat_cuts':x['carat_cuts'],'price':x['price'],'is_f':x['price'].diff()>0,'continuous':((x['price'].diff()>0)!=(x['price'].diff()>0).shift()).cumsum()} ))tp.loc[tp.is_f==True,:].groupby(['carat_cuts','continuous']).price.agg(['count']).reset_index().groupby('carat_cuts').max()##因?yàn)闆](méi)有計(jì)算序列第一個(gè)值。嚴(yán)格遞增最大序列長(zhǎng)度在max的基礎(chǔ)上+1,結(jié)果如下.#(0.0, 0.5] 8#(0.5, 1.0] 8#(1.0, 1.5] 7#(1.5, 2.0] 11#(2.0, 6.0] 7
(d). 請(qǐng)按顏色分組,分別計(jì)算價(jià)格關(guān)于克拉數(shù)的回歸系數(shù)。(單變量的簡(jiǎn)單線性回歸,并只使用Pandas和Numpy完成)
df['ones']=1colors=['G','E','F','H','D','I','J']for c in colors:X=np.matrix( df.loc[ df.color==c, ['carat','ones']].values)Y=np.matrix( df.loc[ df.color==c, ['price']].values)params=np.linalg.inv(X.T@X)@X.T@Yprint('color {}的 參數(shù)為k={},b={}'.format(c,params[0],params[1]) )# color G的 參數(shù)為k=[[8525.34577932]],b=[[-2575.52764286]]
練習(xí)2:有一份關(guān)于美國(guó)10年至17年的非法藥物數(shù)據(jù)集,列分別記錄了年份、州(5個(gè))、縣、藥物類型、報(bào)告數(shù)量,請(qǐng)解決下列問(wèn)題:
pd.read_csv('data/Drugs.csv').head()
(a). 按照年份統(tǒng)計(jì),哪個(gè)縣在哪年的報(bào)告數(shù)量最多?這個(gè)縣所屬的州在當(dāng)年也是報(bào)告數(shù)最多的嗎?
答:按照年份統(tǒng)計(jì),HAMILTON在2017年報(bào)告數(shù)量最多,該縣所屬的州PA在當(dāng)年不是報(bào)告數(shù)最多的。df_ex2.groupby(['YYYY', 'COUNTY'])['DrugReports'].sum().sort_values(ascending = False
df_ex2['State'][df_ex2['COUNTY']?==?'HAMILTON'].unique()array(['PA'], dtype=object)df_ex2.loc[df_ex2['YYYY']?==?2017,?:].groupby('State')['DrugReports'].sum().sort_values(ascending?=?False)

(b). 從14年到15年,Heroin的數(shù)量增加最多的是哪一個(gè)州?它在這個(gè)州是所有藥物中增幅最大的嗎?若不是,請(qǐng)找出符合該條件的藥物。
答:從14年到15年,Heroin的數(shù)量增加最多的是OH,它在這個(gè)州是所有藥物中增幅最大。
方法一
df_ex2_b_1?=?df_ex2.loc[((df_ex2['YYYY']?==?2014)?|?(df_ex2['YYYY']?==?2015))?&?(df_ex2['SubstanceName']?==?'Heroin'),?:]df_ex2_b_2?=?df_ex2_b_1.groupby(['YYYY',?'State'])['DrugReports'].sum().to_frame().unstack(level=0)(df_ex2_b_2[('DrugReports',?2015)]?-?df_ex2_b_2[('DrugReports',?2014)]).sort_values(ascending?=?False)

方法二
df_ex2_b_1?=?df_ex2.loc[((df_ex2['YYYY']?==?2014)?|?(df_ex2['YYYY']?==?2015))?&?(df_ex2['SubstanceName']?==?'Heroin'),?:]df_ex2_b_3 = df_ex2_b_1.groupby(['YYYY', 'State'])['DrugReports'].sum().to_frame()df_ex2_b_3.groupby('State').apply(lambda x:x.loc[2015, :] - x.loc[2014, :]).sort_values(by = 'DrugReports', ascending = False)

df_ex2_b_1?=?df_ex2.loc[((df_ex2['YYYY']?==?2014)?|?(df_ex2['YYYY']?==?2015)),?:]df_ex2_b_2?=?df_ex2_b_1.groupby(['YYYY',?'State',?'SubstanceName'])['DrugReports'].sum().to_frame().unstack(level=0)(df_ex2_b_2[('DrugReports',?2015)]?-?df_ex2_b_2[('DrugReports',?2014)]).sort_values(ascending?=?False)

本文電子版 后臺(tái)回復(fù) Pandas分組 獲取
“在看,為沉迷學(xué)習(xí)點(diǎn)贊↓
