python中分組函數(shù)groupby和分組運算函數(shù)agg的使用
今天來介紹pandas中一個很有用的函數(shù)groupby,其實和hive中的groupby的效果是一樣的,區(qū)別在于兩種語言的寫法問題。groupby在Python中的分組統(tǒng)計中很有用~
groupby:
首先創(chuàng)建數(shù)據(jù):
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': ['a', 'b', 'a', 'c', 'a', 'c', 'b', 'c'],
'B': [2, 7, 1, 3, 3, 2, 4, 8],
'C': [100, 87, 96, 130, 105, 87, 96, 155]})
df
Out[2]:
A B C
0 a 2 100
1 b 787
2 a 196
3 c 3 130
4 a 3 105
5 c 287
6 b 496
pandas中g(shù)roupby的基本操作:
1、按A列進行分組,求B、C兩列的均值:
df.groupby('A').mean()
Out[6]:
B C
A
a 2.000000 100.333333
b 5.50000091.500000
c 4.333333 124.000000
當然也可以按照多列進行分組,獲取其他列的均值:
df.groupby(['A','B']).mean() Out[7]: C A B a 196 2 100 3 105 b 496 787 c 287 3 130 8 155
2、分組后,選擇列進行計算:
data=df.groupby('A')
data['B'].std()
Out[11]:
A
a 1.00000
b 2.12132
c 3.21455
Name: B, dtype: float64
#選擇B、C兩列
data['B','C'].mean()
Out[12]:
B C
A
a 2.000000 100.333333
b 5.50000091.500000
c 4.333333 124.000000
3、按A進行分組后,可以對不同的列采用不同的聚合方法(ps:這一點就和hive很相像了)
data.agg({'B':'mean','C':'sum'}) #B列均值,C列匯總
Out[14]:
CB
A
a 301 2.000000
b 183 5.500000
c 372 4.333333
4、如果按照A進行分組后,對多列采用相同的聚合方法,我們可以借助apply函數(shù):
df.groupby('A').apply(np.mean)
Out[25]:
B C
A
a 2.000000 100.333333
b 5.50000091.500000
c 4.333333 124.000000
5、將某列數(shù)據(jù)按數(shù)據(jù)值分成不同范圍段進行分組運算
創(chuàng)建數(shù)據(jù)集:
np.random.seed(0)
df = pd.DataFrame({'Age': np.random.randint(20, 70, 100), 'Sex': np.random.choice(['Male', 'Female'], 100), 'number_of_foo': np.random.randint(1, 20, 100)})
Out[38]:
Age Sex number_of_foo
064 Female 14
167 Female 14
220 Female 12
323 Male 17
423 Female 15
目標:將age字段分成三組,有如下兩種方法實現(xiàn):
#第一種方法: 1、bins=4 pd.cut(df['Age'], bins=4) 0 (56.75, 69.0] 1 (56.75, 69.0] 2 (19.951, 32.25] 3 (19.951, 32.25] 4 (19.951, 32.25]... #第二種方法 2、bins=[19, 40, 65, np.inf] pd.cut(df['Age'], bins=[19,40,65,np.inf]) Out[40]: 0 (40.0, 65.0] 1(65.0, inf] 2 (19.0, 40.0] 3 (19.0, 40.0] 4 (19.0, 40.0] #分組范圍結(jié)果如下: age_groups = pd.cut(df['Age'], bins=[19,40,65,np.inf]) df.groupby(age_groups).mean() Out[43]: Age number_of_foo Age (19.0, 40.0] 29.840000 9.880000 (40.0, 65.0] 52.833333 9.452381 (65.0, inf]67.375000 9.250000 #按‘Age'分組范圍和性別(sex)進行制作交叉表 pd.crosstab(age_groups, df['Sex']) Out[44]: Sex Female Male Age (19.0, 40.0]22 28 (40.0, 65.0]18 24 (65.0, inf] 3 5
agg:
1、使用groupby按照某列(A)進行分組后,需要對另外一列采用不同的聚合方法:
df.groupby('A')['B'].agg({'mean':np.mean, 'std': np.std})
Out[16]:
stdmean
A
a 1.00000 2.000000
b 2.12132 5.500000
c 3.21455 4.333333
2、按照某列進行分組后,對不同的列采用不同的聚合方法:
df.groupby('A').agg({'B':[np.mean,'sum'],'C':['count',np.std]}) #[]中對應的是兩種方法
Out[17]:
C B
count stdmean sum
A
a 34.509250 2.0000006
b 26.363961 5.500000 11
c 3 34.394767 4.333333 13
transform:
前面兩種方法得到的結(jié)果是以A列值為索引的結(jié)果,如果使用沒有進行g(shù)roupby分組的index的話,該怎么操作呢?此時就要用到transform函數(shù)了。transform(func, args, *kwargs) 方法簡化了這個過程,: func 參數(shù)應用到所有分組,然后把結(jié)果放置到原數(shù)組的 index 上:
df
Out[31]:
A B C
0 a 2 100
1 b 787
2 a 196
3 c 3 130
4 a 3 105
5 c 287
6 b 496
7 c 8 155
df.groupby('A')['B','C'].transform('count') #注:count函數(shù)在計算時,不計算nan值
Out[32]:
B C
0 3 3
1 2 2
2 3 3
3 3 3
4 3 3
5 3 3
6 2 2
7 3 3
從中可以看出:按A列進行分組,對B、C兩列進行計數(shù)時,B為a的索引有[0,2,4],所以結(jié)果列的中[0,2,4]索引的值都為3,相當于廣播了。對于C列,同理。
到此這篇關(guān)于python中分組函數(shù)groupby和分組運算函數(shù)agg的使用的文章就介紹到這了,更多相關(guān)python 分組函數(shù)groupby和分組運算函數(shù)agg內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信