摘要
進行數(shù)據(jù)分析時,GroupBy分組統(tǒng)計是非常常用的操作,也是十分重要的操作之一。基本上大部分的數(shù)據(jù)分析都會用到該操作,本文將對Python的GroupBy分組統(tǒng)計操作進行講解。
碼字不易,喜歡請點贊,謝謝!!!
1.GroupBy過程
首先看看分組聚合的過程,主要包括拆分(split)、應(yīng)用(Apply)和合并(Combine)
2.創(chuàng)建DataFrame
import pandas as pd
ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',
'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],
'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],
'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],
'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}
df = pd.DataFrame(ipl_data)
df
3.將df按照Team列分組
分組之后的grouped是個DataFrameGroupBy對象
grouped = df.groupby('Team')
grouped
4.查看df按照Team分組之后結(jié)果
按照不同的Team值來分組
grouped.groups
5.分組后的結(jié)果對Points求和
grouped['Points'].sum()
分組后常用操作包括:求和(sum)、平均值(mean)、計數(shù)(count)等等,如下圖。
6.根據(jù)任意長度適當(dāng)?shù)臄?shù)組分組
import numpy as np
key1 = np.array(list('abababbaaabb'))
df.groupby(key1).Team.count()
7.對分組進行迭代
GroupBy分組產(chǎn)生的是一組二元元組,有分組名和數(shù)據(jù)塊組成。即(分組名、數(shù)據(jù)塊)。
for name,group in df.groupby('Team'):
print(name)
print(group)
print('*******分隔符*********')
另外,對于多重建分組的情況,元組的第一個元素將是由元組組成。
即((分組名1,分組名2)、數(shù)據(jù)塊)。
for (name1,name2),group in df.groupby(['Team','Rank']):
print(name1)
print(name2)
print(group)
print('*******分隔符*********')
8.在不同軸上分組
GroupBy默認是在axis=0軸上進行分組的,也可以在axis=1軸上進行分組聚合,不過用的相對較少。
df.dtypes
grouped = df.groupby(df.dtypes, axis=1)
grouped.groups
9.通過字典或Series進行分組
people = pd.DataFrame(np.random.randn(5, 5),
columns=['a', 'b', 'c', 'd', 'e'],
index=['Joe', 'Steve', 'Wes', 'Jim','Travis'])
people.iloc[2:3, [1, 2]] = np.nan
people
mapping = {'a': 'red', 'b': 'red', 'c': 'blue',
'd': 'blue', 'e': 'red', 'f' : 'orange'}
by_column = people.groupby(mapping, axis=1)
by_column.sum()
map_series = pd.Series(mapping)
people.groupby(map_series, axis=1).count()
10.通過函數(shù)進行分組
people.groupby(len).sum()
11.函數(shù)、數(shù)組、列表、字典、Series組合分組
key_list = ['one', 'one', 'one', 'two', 'two']
people.groupby([len, key_list]).min()
12.根據(jù)索引級別分組
回到最初的DataFrame,給他重新定義成雙層索引,并且給索引命名
df.columns = ([['a','a','a','b'],['Team', 'Rank', 'Year', 'Points']])
df.columns.names = ['one','two']
df
df.groupby(level='one',axis=1).count()
12.多函數(shù)聚合
其中多函數(shù)聚合中也可以使用自定義函數(shù)。
df.columns = ['Team','Rank','Year','Points']
df.groupby('Team')['Points'].agg(['sum','mean','std'])
13.apply:一般性的“拆分-應(yīng)用-合并”
定義函數(shù):
def top(df,n=2,column='Points'):
return df.sort_index(by=column,ascending=False)[:n]
應(yīng)用:
df.groupby('Team').apply(top)
df.groupby('Team').apply(top,n=3)
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
