數(shù)據(jù)的分組運(yùn)算和聚合
在將數(shù)據(jù)集加載、融合、準(zhǔn)備好之后,通常就是計(jì)算分組統(tǒng)計(jì)或?成透視表, pandas提供了
?個(gè)靈活?效的groupby功能,它使你能以?種?然的?式對(duì)數(shù)據(jù)集進(jìn)?切?、切塊、摘要等
操作
1. 分組機(jī)制 -- GroupBy
分組運(yùn)算"split-apply-combine"(拆分-應(yīng)?-合并)。第?個(gè)階段,pandas對(duì)象
(?論是Series、DataFrame還是其他的)中的數(shù)據(jù)會(huì)根據(jù)你所提供的?個(gè)或多個(gè)鍵被拆分
(split)為多組。拆分操作是在對(duì)象的特定軸上執(zhí)?的。例如,DataFrame可以在其?
(axis=0)或列(axis=1)上進(jìn)?分組。然后,將?個(gè)函數(shù)應(yīng)?(apply)到各個(gè)分組并產(chǎn)
??個(gè)新值。最后,所有這些函數(shù)的執(zhí)?結(jié)果會(huì)被合并(combine)到最終的結(jié)果對(duì)象中
df = pd.DataFrame({'key1' : ['a', 'a', 'b', 'b', 'a'],
....: 'key2' : ['one', 'two', 'one', 'two', 'one'],
....: 'data1' : np.random.randn(5),
....: 'data2' : np.random.randn(5)})
grouped = df['data1'].groupby(df['key1'])
變量grouped是?個(gè)GroupBy對(duì)象。它實(shí)際上還沒(méi)有進(jìn)?任何計(jì)算,只是含有?些有關(guān)分組鍵df[‘key1’]的中間數(shù)據(jù)?已
grouped.mean() # 對(duì)分組的數(shù)據(jù)求平均值,索引是key1列去重后的值
means = df['data1'].groupby([df['key1'], df['key2']]).mean() # ?次傳?多個(gè)數(shù)組的列表,外層索引為key1,內(nèi)層索引為key2,數(shù)據(jù)為data1的平均值
means.unstack() # 轉(zhuǎn)置,默認(rèn)把外層索引變?yōu)榱兴饕?,傳入?yún)?shù)1默認(rèn)將內(nèi)層索引變?yōu)榱兴饕?
GroupBy的size?法,它可以返回?個(gè)含有分組??的Series(填充數(shù)據(jù)為每一組包含的原始數(shù)據(jù)個(gè)數(shù))
df.groupby(['key1', 'key2']).size()
2.對(duì)分組進(jìn)行迭代:
GroupBy對(duì)象?持迭代,可以產(chǎn)??組?元元組(由分組名和數(shù)據(jù)塊組成)
a. 單一分組鍵情況:
for name, group in df.groupby('key1'):
....: print(name)
....: print(group)
輸出如下:
a
data1 data2 key1 key2
0 -0.204708 1.393406 a one
1 0.478943 0.092908 a two
4 1.965781 1.246435 a one
b
data1 data2 key1 key2
2 -0.519439 0.281746 b one
3 -0.555730 0.769023 b two
b. 多重分組鍵情況(元組的第?個(gè)元素將會(huì)是由鍵值組成的元組):
for (k1, k2), group in df.groupby(['key1', 'key2']):
....: print((k1, k2))
....: print(group)
輸出如下:
('a', 'one')
data1 data2 key1 key2
0 -0.204708 1.393406 a one
4 1.965781 1.246435 a one
('a', 'two')
data1 data2 key1 key2
1 0.478943 0.092908 a two
('b', 'one')
data1 data2 key1 key2
2 -0.519439 0.281746 b one
('b', 'two')
data1 data2 key1 key2
3 -0.55573 0.769023 b two
pieces = dict(list(df.groupby('key1'))) # 將分組后的數(shù)據(jù)做成一個(gè)字典(只能是一個(gè)分組鍵)
pieces['b'] # 通過(guò)key1的值拿到相應(yīng)片段的數(shù)據(jù)集
3. 根據(jù)dtypes對(duì)列進(jìn)行分組--df.dtypes輸出字段對(duì)應(yīng)數(shù)據(jù)類(lèi)型(float64,object等)
grouped = df.groupby(df.dtypes, axis=1)
for dtype, group in grouped:
....: print(dtype)
....: print(group)
輸出如下:
float64
data1 data2
0 -0.204708 1.393406
1 0.478943 0.092908
2 -0.519439 0.281746
3 -0.555730 0.769023
4 1.965781 1.246435
object
key1 key2
0 a one
1 a two
2 b one
3 b two
4 a one
4. 分組后選取分組的一列或者列的子集(默認(rèn)是按行分組)
df.groupby('key1')['data1'] # 取一列(結(jié)果還是分組對(duì)象)
df.groupby('key1')[['data1','data2']] # 取多列(結(jié)果還是分組對(duì)象)
df.groupby(['key1', 'key2'])[['data2']].mean() # 分組后取data2列的數(shù)據(jù),按組求每一組data2的平均,返回一個(gè)dataframe(兩層索引,key1和key2)
5.根據(jù)字典或者Sreies分組
people = pd.DataFrame(np.random.randn(5, 5),
....: columns=['a', 'b', 'c', 'd', 'e'],
....: index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])
mapping = {'a': 'red', 'b': 'red', 'c': 'blue',
....: 'd': 'blue', 'e': 'red', 'f' : 'orange'}
根據(jù)字典分組,再對(duì)每組求和(默認(rèn)按行分組,如果設(shè)置axis=1按列分組,那么就按列求和):
by_dict = people.groupby(mapping, axis=1).sum()
根據(jù)Series分組(按列分組,那么就按列求和)
map_series = pd.Series(mapping)
by_series = people.groupby(map_series, axis=1).count()
6.通過(guò)函數(shù)進(jìn)行分組:
使?Python函數(shù)是?種更原?的?法定義分組映射。任何被當(dāng)做分組鍵的函數(shù)都會(huì)在各個(gè)索引值上被調(diào)??次,其返回值就會(huì)被?作分組名稱(chēng)
people.groupby(len).sum() # 根據(jù)people的行索引的長(zhǎng)度分組,再對(duì)每組每列所有行數(shù)據(jù)求和
key_list = ['one', 'one', 'one', 'two', 'two']
people.groupby([len, key_list]).min() # 根據(jù)行索引長(zhǎng)度和key_list來(lái)分組再取分組后每組每列所有行中的最小值作為填充數(shù)據(jù)(外層索引len的返回值的去重值,內(nèi)層索引key_list去重的值)
7.通過(guò)索引級(jí)別來(lái)分組:
層次化索引數(shù)據(jù)集最?便的地?就在于它能夠根據(jù)軸索引的?個(gè)級(jí)別進(jìn)?聚合,要根據(jù)級(jí)別分組,使?level關(guān)鍵字傳遞級(jí)別序號(hào)或名字
columns = pd.MultiIndex.from_arrays([['US', 'US', 'US', 'JP', 'JP'],
....: [1, 3, 5, 1, 3]],
....: names=['cty', 'tenor']) # 創(chuàng)建名字為為cty外層索引,名字為tenor的內(nèi)層索引
hier_df = pd.DataFrame(np.random.randn(4, 5), columns=columns) # 創(chuàng)建dataframe,列索引為columns
hier_df.groupby(level='cty', axis=1).count() # 分組鍵為cty層索引,按列分組,再統(tǒng)計(jì)每組每行的列數(shù)
數(shù)據(jù)的聚合
聚合指的是任何能夠從數(shù)組產(chǎn)?標(biāo)量值的數(shù)據(jù)轉(zhuǎn)換過(guò)程,?如mean、count、min以及sum等
1. 聚合函數(shù):
第一種.pandas內(nèi)置聚合函數(shù):
count 分組中非NA值的數(shù)量
sum 非NA值的和
mean 非NA值的平均值
median 非NA值的算術(shù)中位數(shù)
std、var 無(wú)偏(分母為n-1)標(biāo)準(zhǔn)差和方差
min、max 非NA值的最小和最大值
prod 非NA值的極
first、last 第一個(gè)和最后一個(gè)非NA值
第二種.自定義聚合函數(shù)(傳入aggregate或者agg方法):
def peak_to_peak(arr):
....: return arr.max() - arr.min()
grouped.agg(peak_to_peak)
2. 面向列的多函數(shù)應(yīng)用(默認(rèn)將作為分組條件的列變?yōu)樾兴饕?,多個(gè)條件列則變?yōu)閷哟位饕?/h2>
tips = pd.read_csv('examples/tips.csv')
tips['tip_pct'] = tips['tip'] / tips['total_bill']
grouped = tips.groupby(['day', 'smoker'])
grouped_pct = grouped['tip_pct']
grouped_pct.agg('mean') # 每個(gè)分組對(duì)tip_pct數(shù)據(jù)求平均,輸出兩層行索引和一列數(shù)據(jù)(共3列)
傳??組函數(shù)或函數(shù)名,得到的DataFrame的列就會(huì)以相應(yīng)的函數(shù)命名:
grouped_pct.agg(['mean', 'std', peak_to_peak]) # 輸出兩層索引和三列數(shù)據(jù)(共5列)
傳?的是?個(gè)由(name,function)元組組成的列表,則各元組的第?個(gè)元素就會(huì)被?作DataFrame的列名:
grouped_pct.agg([('foo', 'mean'), ('bar', np.std)])
對(duì)兩列數(shù)據(jù)計(jì)算三個(gè)統(tǒng)計(jì)數(shù)據(jù):
result = grouped['tip_pct', 'total_bill'].agg(['count', 'mean', 'max'])
result['tip_pct'] # 取出tip_pct數(shù)據(jù)的統(tǒng)計(jì)信息,返回一個(gè)dataframe
傳入元祖自定義默認(rèn)的統(tǒng)計(jì)名(函數(shù)名)
grouped['tip_pct', 'total_bill'].agg([('Dur', 'mean'),('Abw', np.var)])
對(duì)?個(gè)列或不同的列應(yīng)?不同的函數(shù),向agg傳??個(gè)從列名映射到函數(shù)的字典
grouped.agg({'tip' : np.max, 'size' : 'sum'})
grouped.agg({'tip_pct' : ['min', 'max', 'mean', 'std'],'size' : 'sum'})
傳入as_index=False 阻止將作為分組條件的列變?yōu)樗饕?,保留為?shù)據(jù);對(duì)結(jié)果調(diào)?reset_index也能
得到這種形式的結(jié)果。但使?as_index=False?法可以避免?些不必要的計(jì)算
tips.groupby(['day', 'smoker'], as_index=False).mean()