Pandas分組聚合之groupby()、agg()方法的使用教程
創(chuàng)建一個dataframe結構
import pandas as pd df = pd.DataFrame( data={ 'name': ['z_s', 'l_s', 'w_w', 'z_l', 'y_s', 'j_j', 'l_b', 'z_f', 'hs_q', 'lbl_k', 'qy_n', 'mg_n'], 'score': [100, 97, 98, 89, 67, 59, 29, 87, 78, 89, 88, 80], 'group': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], 'cls': ['A', 'A', 'A', 'B', 'B', 'B', 'A', 'A', 'A', 'B', 'B', 'B'], 'height': [178.0, 180.0, 176.0, 182.0, 189.0, 190.0, 172.5, 175.0, 165.0, 160.0, 158.5, 159.0] }, index=['stu_' + str(i) for i in np.arange(1, 13, 1)] ) print('df:\n', df)
分組函數(shù) groupby()
初識分組聚合
我們可以通過DataFrame.groupby(by=[”column“]) 方法對數(shù)據(jù)進行分組,再根據(jù)需求進行 聚合操作。
統(tǒng)計各個班的最高的成績:
# 先按照班級進行分組,再統(tǒng)計各個組里面的成績的最大值! ret = df.groupby(by=['cls'])['score'].max().reset_index() print('ret:\n', ret)
分開來看就是:
ret = df.groupby(by=['cls']) # 將數(shù)據(jù)以 cls 進行分組,返回 DataFrameGroupBy 對象 print(ret) # <pandas.core.groupby.generic.DataFrameGroupBy object at 0x000002B6B2003A60> ret = ret['score'] # 取出 score 列,返回 SeriesGroupBy 對象 print(ret) # <pandas.core.groupby.generic.SeriesGroupBy object at 0x000002B6B59EAFD0> ret = ret.max() # 取出 score 中的最大值,返回 Series 對象 print(ret) """ cls A 100 B 89 Name: score, dtype: int64 """ ret = ret.reset_index() # 重設索引,返回 DataFrame 對象 print(ret) """ cls score 0 A 100 1 B 89 """
多重行索引分組聚合
統(tǒng)計各個班的各個小組的最高成績
# 先按照班級分組,再按照小組分組,最后統(tǒng)計各個小組內(nèi)成績的最大值 ret = df.groupby(by=['cls', 'group'])['score'].max() print('ret:\n', ret) print('index:\n', ret.index) # MultiIndex ---多重行索引 ret = ret.reset_index() # 重設索引 print(ret)
對多列數(shù)據(jù)進行分組聚合
統(tǒng)計各個班級的成績、身高的平均值:
# 按照班級分組,統(tǒng)計各個組內(nèi) 成績、身高的平均值 ret = df.groupby(by=['cls'])[['score', 'height']].mean().reset_index() print('ret:\n', ret)
綜合應用
統(tǒng)計各個班級、各個小組的成績、身高的平均值
# 先按照班級分組、再按照小組分組---統(tǒng)計各個小組內(nèi)的成績的平均值、身高的平均值 ret = df.groupby(by=['cls', 'group'])[['score', 'height']].mean().reset_index() print('ret:\n', ret)
聚合函數(shù) agg(aggregate)
在Pandas中,
agg
和aggregate
兩個函數(shù)指向同一個方法,使用時寫任意一個即可。
求 多列數(shù)據(jù) 的 多個指標
統(tǒng)計成績、身高的最大值、均值
# 使用agg 方法 可以對多列數(shù)據(jù)一次性求出多個指標 ret = df.loc[:, ['score', 'height']].agg([np.max, np.mean]) print('ret:\n', ret)
對多列數(shù)據(jù)統(tǒng)計不同的指標
統(tǒng)計成績的均值、同時統(tǒng)計身高的最大值
ret = df.agg({'score': [np.mean], 'height': [np.max]}) print('ret:\n',ret)
對多列數(shù)據(jù)統(tǒng)計不同個數(shù)的指標
統(tǒng)計成績的均值、最大值、中位數(shù) 和 身高的均值
ret = df.agg({'score': [np.mean, np.max, np.median], 'height': [np.mean]}) print('ret:\n', ret)
使用agg 方法也可以配合著 分組 對不同列、不同的數(shù)據(jù)、統(tǒng)計不同個數(shù)的 不同指標!
ret = df.groupby(by=['cls']).agg({'height': [np.max,np.mean], 'score': [np.min]}) print('ret:\n', ret)
agg調用 自定義函數(shù)
ret = df.loc[:, 'score'].agg(lambda x: x + 1) print('ret1:\n', ret) def func_add_one(x): return x + 1 ret = df.loc[:, 'score'].agg(func_add_one) print('ret2:\n', ret) # 對多列 使用自定義函數(shù) ret = df.loc[:, ['score', 'height']].agg(func_add_one) print('ret3:\n', ret)
使用agg 調用numpy的統(tǒng)計指標
# 統(tǒng)計所有同學成績的和 ret = df.loc[:, 'score'].agg(np.sum) print('ret:\n',ret) print('type:\n',type(ret)) # # 統(tǒng)計所有同學 成績以及身高 的和 ret = df.loc[:, ['score', 'height']].agg(np.sum) print('ret:\n', ret) print('type:\n',type(ret)) # 統(tǒng)計身高 + 成績(無意義的,只是為了演示能夠 同一行相加) ret = df.loc[:, ['score', 'height']].agg(np.sum, axis=1) # 使用axis指定相加的方向 print('ret:\n', ret) print('type:\n',type(ret))
除了以上方法之外,還可以使用自定義方法聚合,可以參見我的這篇文章:Pandas使用自定義方法
總結
到此這篇關于Pandas分組聚合之groupby()、agg()方法使用的文章就介紹到這了,更多相關Pandas分組聚合groupby()、agg()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Windows 下更改 jupyterlab 默認啟動位置的教程詳解
這篇文章主要介紹了Windows 下更改 jupyterlab 默認啟動位置,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05Django中更新多個對象數(shù)據(jù)與刪除對象的方法
這篇文章主要介紹了Django中更新多個對象數(shù)據(jù)與刪除對象的方法,Django是Python重多各色框架中人氣最高的一個,需要的朋友可以參考下2015-07-07Python實現(xiàn)繪制多種激活函數(shù)曲線詳解
所謂激活函數(shù)(Activation?Function),就是在人工神經(jīng)網(wǎng)絡的神經(jīng)元上運行的函數(shù),負責將神經(jīng)元的輸入映射到輸出端。這篇文章主要介紹了Python如何實現(xiàn)繪制多種激活函數(shù)曲線,希望對大家有所幫助2023-04-04Pytorch中index_select() 函數(shù)的實現(xiàn)理解
這篇文章主要介紹了Pytorch中index_select() 函數(shù)的實現(xiàn)理解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11