Pandas作分析數據,能夠分爲索引、分組、變形及合併四種操做。以前介紹過索引操做,如今接着對Pandas中的分組操做進行介紹:主要包含SAC含義、groupby函數、聚合、過濾和變換、apply函數。文章的最後,根據今天的知識介紹,給出了6個問題與2個練習,供你們學習實踐。數據結構
在詳細講解每一個模塊以前,首先讀入數據:app
import numpy as npimport pandas as pddf = pd.read_csv('data/table.csv',index_col='ID')df.head()
通過groupby後會生成一個groupby對象,該對象自己不會返回任何內容,只有當相應的方法被調用纔會起做用。dom
1. 分組函數的基本內容:ide
根據某一列分組函數
根據某幾列分組
工具
組容量與組數
學習
組的遍歷spa
level參數(用於多級索引)和axis參數設計
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.ngroupsgrouped_mul.ngroups
for name,group in grouped_single: print(name) display(group.head())
e). level參數(用於多級索引)和axis參數code
df.set_index(['Gender','School']).groupby(level=1,axis=0).get_group('S_1').head()
2. groupby對象的特色:
分組對象的head 和first
分組依據
groupby的[]操做
print([attr for attr in dir(grouped_single) if not attr.startswith('_')])
grouped_single.head(2)
first顯示的是以分組爲索引的每組的第一個分組信息
grouped_single.first()
df.groupby(np.random.choice(['a','b','c'],df.shape[0])).get_group('a').head()# 至關於將np.random.choice(['a','b','c'],df.shape[0])當作新的一列進行分組
df[:5].groupby(lambda x:print(x)).head(0)
df.groupby(lambda x:'奇數行' if not df.index.get_loc(x)%2==1 else '偶數行').groups
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)
df.groupby(['Gender','School'])['Math'].mean()>=60
用列表可選出多個屬性列:
df.groupby(['Gender','School'])[['Math','Height']].mean()
bins = [0,40,60,80,90,100]cuts = pd.cut(df['Math'],bins=bins) #可選label添加自定義標籤df.groupby(cuts)['Math'].count()
1. 聚合
經常使用聚合函數
同時使用多個聚合函數
使用自定義函數
利用NameAgg函數
帶參數的聚合函數
group_m = grouped_single['Math']group_m.std().values/np.sqrt(group_m.count().values)== group_m.sem().values
group_m.agg(['sum','mean','std'])
group_m.agg([('rename_sum','sum'),('rename_mean','mean')])
指定哪些函數做用哪些列
grouped_mul.agg({'Math':['mean','max'],'Height':'var'})
grouped_single['Math'].agg(lambda x:print(x.head(),'間隔'))#能夠發現,agg函數的傳入是分組逐列進行的,有了這個特性就能夠作許多事情
官方沒有提供極差計算的函數,但經過agg能夠容易地實現組內極差計算
grouped_single['Math'].agg(lambda x:x.max()-x.min())
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()
def f(s,low,high): return s.between(low,high).max()grouped_single['Math'].agg(f,50,52)
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__ = name return wrappernew_f = agg_f(f_test,'at_least_one_in_50_52',50,52)grouped_single['Math'].agg([new_f,'mean']).head()
2. 過濾 Filteration
filter函數是用來篩選某些組的(務必記住結果是組的全體),所以傳入的值應當是布爾標量。
grouped_single[['Math','Physics']].filter(lambda x:(x['Math']>32).all()).head()
3. 變換 Transformation
傳入對象
利用變換方法進行組內標準化
利用變換方法進行組內缺失值的均值填充
grouped_single[['Math','Height']].transform(lambda x:x-x.min()).head()
grouped_single[['Math','Height']].transform(lambda x:x.mean()).head()
grouped_single[['Math','Height']].transform(lambda x:(x-x.mean())/x.std()).head()
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()
1. apply函數的靈活性
標量返回值
列表返回值
數據框返回值
df.groupby('School').apply(lambda x:print(x.head(1)))
df[['School','Math','Height']].groupby('School').apply(lambda x:x.max())
b). 列表返回值
df[['School','Math','Height']].groupby('School').apply(lambda x:x-x.min()).head()
c). 數據框返回值
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同時統計多個指標
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)
問題
問題1. 什麼是fillna的前向/後向填充,如何實現?
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方法能夠控制參數的填充方式,是向上填充:將缺失值填充爲該列中它上一個未缺失值;向下填充相反
method : {‘backfill', ‘bfill', ‘pad', ‘ffill', None}, default None
pad / ffill: 向下自動填充
backfill / bfill: 向上自動填充
df_nan.Math=df_nan.Math.fillna(method='pad')df_nan.head()
問題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)
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) 缺失值補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)
問題3. 如何計算組內0.25分位數與0.75分位數?要求顯示在同一張表上。
gp.apply(lambda x:pd.DataFrame({'q25':x.quantile(0.25), 'q75':x.quantile(0.75) }))問題4. 既然索引已經可以選出某些符合條件的子集,那麼filter函數的設計有什麼意義? 答:filter函數是用來篩選組的,結果是組的全體。 問題5. 整合、變換、過濾三者在輸入輸出和功能上有何異同?
整合(Aggregation)分組計算統計量:輸入的是每組數據,輸出是每組的統計量,在列維度上是標量。
變換(Transformation):即分組對每一個單元的數據進行操做(如元素標準化):輸入的是每組數據,輸出是每組數據通過某種規則變換後的數據,不改變數據的維度。
問題6. 在帶參數的多函數聚合時,有辦法可以繞過wrap技巧實現一樣功能嗎?
def f_test(s,low=50,high=52): return s.between(low,high).max()grouped_single['Math'].agg([f_test,'mean']).head()#這裏須要理解的是,agg除了傳入字符形式的np函數外,其餘傳入對象也應當是一個函數
練習
df=pd.read_csv('data/Diamonds.csv')df.head(3)
df.groupby(lambda x : '>1克拉' if df.loc[x,'carat']>1.0 else '<=1克拉').price.agg(lambda x:x.max()-x.min()
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)##有些是單位質量最貴的,有些不是(當count_diff與mean_diff同爲0時,則是)
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)#再求價格遞增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()
##由於沒有計算序列第一個值。嚴格遞增最大序列長度在max的基礎上+1,結果以下.#(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
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@Y print('color {}的 參數爲k={},b={}'.format(c,params[0],params[1]) )
# color G的 參數爲k=[[8525.34577932]],b=[[-2575.52764286]]# color E的 參數爲k=[[8296.21278346]],b=[[-2381.04960038]]# color F的 參數爲k=[[8676.65834379]],b=[[-2665.80619085]]# color H的 參數爲k=[[7619.0983199]],b=[[-2460.41804636]]# color D的 參數爲k=[[8408.35312588]],b=[[-2361.01715228]]# color I的 參數爲k=[[7761.04116881]],b=[[-2878.15035558]]# color J的 參數爲k=[[7094.19209226]],b=[[-2920.60333719]]
練習2:有一份關於美國10年至17年的非法藥物數據集,列分別記錄了年份、州(5個)、縣、藥物類型、報告數量,請解決下列問題:
pd.read_csv('data/Drugs.csv').head()
答:按照年份統計,HAMILTON在2017年報告數量最多,該縣所屬的州PA在當年不是報告數最多的。
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)
答:從14年到15年,Heroin的數量增長最多的是OH,它在這個州是全部藥物中增幅最大。
方法一
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)