pandas中g(shù)roupby操作實(shí)現(xiàn)
一、實(shí)驗(yàn)?zāi)康?/h2>
熟練掌握pandas中的groupby操作
二、實(shí)驗(yàn)原理
groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False)
參數(shù)說明:
- by是指分組依據(jù)(列表、字典、函數(shù),元組,Series)
- axis:是作用維度(0為行,1為列)
- level:根據(jù)索引級別分組
- sort:對groupby分組后新的dataframe中索引進(jìn)行排序,sort=True為升序,
- as_index:在groupby中使用的鍵是否成為新的dataframe中的索引,默認(rèn)as_index=True
- group_keys:在調(diào)用apply時,將group鍵添加到索引中以識別片段
- squeeze :如果可能的話,減少返回類型的維數(shù),否則返回一個一致的類型
grouping操作(split-apply-combine)
數(shù)據(jù)的分組&聚合 – 什么是groupby 技術(shù)?
在數(shù)據(jù)分析中,我們往往需要在將數(shù)據(jù)拆分,在每一個特定的組里進(jìn)行運(yùn)算。比如根據(jù)教育水平和年齡段計算某個城市的工作人口的平均收入。
pandas中的groupby提供了一個高效的數(shù)據(jù)的分組運(yùn)算。
我們通過一個或者多個分類變量將數(shù)據(jù)拆分,然后分別在拆分以后的數(shù)據(jù)上進(jìn)行需要的計算
我們可以把上述過程理解為三部:
1.拆分?jǐn)?shù)據(jù)(split)
2.應(yīng)用某個函數(shù)(apply)
3.匯總計算結(jié)果(aggregate)
下面這個演示圖展示了“分拆-應(yīng)用-匯總”的groupby思想

上圖所示,分解步驟:
Step1 :數(shù)據(jù)分組—— groupby 方法
Step2 :數(shù)據(jù)聚合:
使用內(nèi)置函數(shù)——sum / mean / max / min / count等
使用自定義函數(shù)—— agg ( aggregate ) 方法
自定義更豐富的分組運(yùn)算—— apply 方法
三、實(shí)驗(yàn)環(huán)境
Python 3.6.1
Jupyter
四、實(shí)驗(yàn)內(nèi)容
練習(xí)pandas中的groupby的操作案例
五、實(shí)驗(yàn)步驟
1.創(chuàng)建一個數(shù)據(jù)幀df。
import numpy as np
import pandas as pd
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],'C' : np.random.randn(8),'D' : np.random.randn(8)})
print(df)

2.通過A列對df進(jìn)行分布操作。
df.groupby('A') 
3.通過A、B列對df進(jìn)行分組操作。
df.groupby(['A','B'])

4…使用自定義函數(shù)進(jìn)行分組操作,自定義一個函數(shù),使用groupby方法并使用自定義函數(shù)給定的條件,按列對df進(jìn)行分組。
def get_letter_type(letter):
if letter.lower() in 'aeiou':
return 'vowel'
else:
return 'consonant'
grouped = df.groupby(get_letter_type, axis=1)
for group in grouped:
print(group)

5.創(chuàng)建一個Series名為s,使用groupby根據(jù)s的索引對s進(jìn)行分組,返回分組后的新Series,對新Series進(jìn)行first、last、sum操作。
lst = [1, 2, 3, 1, 2, 3] s = pd.Series([1, 2, 3, 10, 20, 30], lst) grouped = s.groupby(level=0) #查看分組后的第一行數(shù)據(jù) grouped.first() #查看分組后的最后一行數(shù)據(jù) grouped.last() #對分組的各組進(jìn)行求和 grouped.sum()

6.分組排序,使用groupby進(jìn)行分組時,默認(rèn)是按分組后索引進(jìn)行升序排列,在groupby方法中加入sort=False參數(shù),可以進(jìn)行降序排列。
df2=pd.DataFrame({'X':['B','B','A','A'],'Y':[1,2,3,4]})
#按X列對df2進(jìn)行分組,并求每組的和
df2.groupby(['X']).sum()
#按X列對df2進(jìn)行分組,分組時不對鍵進(jìn)行排序,并求每組的和
df2.groupby(['X'],sort=False).sum()

7.使用get_group方法得到分組后某組的值。
df3 = pd.DataFrame({'X' : ['A', 'B', 'A', 'B'], 'Y' : [1, 4, 3, 2]})
#按X列df3進(jìn)行分組,并得到A組的df3值
df3.groupby(['X']).get_group('A')
#按X列df3進(jìn)行分組,并得到B組的df3值
df3.groupby(['X']).get_group('B')

8.使用groups方法得到分組后所有組的值。
df.groupby('A').groups
df.groupby(['A','B']).groups

9.多級索引分組,創(chuàng)建一個有兩級索引的Series,并使用兩個方法對Series進(jìn)行分組并求和。
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] index=pd.MultiIndex.from_arrays(arrays,names=['first','second']) s=pd.Series(np.random.randn(8),index=index) s.groupby(level=0).sum() s.groupby(level='second').sum()

10.復(fù)合分組,對s按first、second進(jìn)行分組并求和。
s.groupby(level=['first', 'second']).sum()

11.復(fù)合分組(按索引和列),創(chuàng)建數(shù)據(jù)幀df,使用索引級別和列對df進(jìn)行分組。
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
df = pd.DataFrame({'A': [1, 1, 1, 1, 2, 2, 3, 3], 'B': np.arange(8)},index=index)
print(df)
df.groupby([pd.Grouper(level=1),'A']).sum()

12.對df進(jìn)行分組,將分組后C列的值賦值給grouped,統(tǒng)計grouped中每類的個數(shù)。
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],'C' : np.random.randn(8),'D' : np.random.randn(8)})
grouped=df.groupby(['A'])
grouped_C=grouped['C']
print(grouped_C.count())

13.對上面創(chuàng)建的df的C列,按A列值進(jìn)行分組并求和。
df['C'].groupby(df['A']).sum()

14.遍歷分組結(jié)果,通過A,B兩列對df進(jìn)行分組,分組結(jié)果的組名為元組。
for name, group in df.groupby(['A', 'B']):
print(name)
print(group)

15.通過A列對df進(jìn)行分組,并查看分組對象的bar列。
df.groupby(['A']).get_group(('bar')) 
16.按A,B兩列對df進(jìn)行分組,并查看分組對象中bar、one都存在的部分。
df.groupby(['A','B']).get_group(('bar','one')) 
注意:當(dāng)分組按兩列來分時,查看分組對象也應(yīng)該包含每列的一部分。
17.聚合操作,按A列對df進(jìn)行分組,使用聚合函數(shù)aggregate求每組的和。
grouped=df.groupby(['A']) grouped.aggregate(np.sum)

按A、B兩列對df進(jìn)行分組,并使用聚合函數(shù)aggregate對每組求和。
grouped=df.groupby(['A']) grouped.aggregate(np.sum)

注意:通過上面的結(jié)果可以看到。聚合完成后每組都有一個組名作為新的索引,使用as_index=False可以忽略組名。
18.當(dāng)as_index=True時,在groupby中使用的鍵將成為新的dataframe中的索引。按A、B兩列對df進(jìn)行分組,這是使參數(shù)as_index=False,再使用聚合函數(shù)aggregate求每組的和.
grouped=df.groupby(['A','B'],as_index=False) grouped.aggregate(np.sum)

19.聚合操作,按A、B列對df進(jìn)行分組,使用size方法,求每組的大小。返回一個Series,索引是組名,值是每組的大小。
grouped=df.groupby(['A','B']) grouped.size()

20.聚合操作,對分組grouped進(jìn)行統(tǒng)計描述。
grouped.describe()

注意:聚合函數(shù)可以減少數(shù)據(jù)幀的維度,常用的聚合函數(shù)有:mean、sum、size、count、std、var、sem 、describe、first、last、nth、min、max。
執(zhí)行多個函數(shù)在一個分組結(jié)果上:在分組返回的Series中我們可以通過一個聚合函數(shù)的列表或一個字典去操作series,返回一個DataFrame。
到此這篇關(guān)于pandas中g(shù)roupby操作實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)pandas groupby操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- pandas groupby()的使用小結(jié)
- Pandas實(shí)現(xiàn)groupby分組統(tǒng)計方法實(shí)例
- pandas中df.groupby()方法深入講解
- pandas?groupby?用法實(shí)例詳解
- Pandas數(shù)據(jù)分析之groupby函數(shù)用法實(shí)例詳解
- pandas中pd.groupby()的用法詳解
- 詳解Pandas中GroupBy對象的使用
- Pandas實(shí)現(xiàn)groupby分組統(tǒng)計的實(shí)踐
- Pandas中GroupBy具體用法詳解
- Pandas分組函數(shù)groupby的用法詳解
相關(guān)文章
淺談Tensorflow由于版本問題出現(xiàn)的幾種錯誤及解決方法
今天小編就為大家分享一篇淺談Tensorflow由于版本問題出現(xiàn)的幾種錯誤及解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
python3 pathlib庫Path類方法總結(jié)
這篇文章主要介紹了python3 pathlib庫Path類方法總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12
使用python實(shí)現(xiàn)時間序列白噪聲檢驗(yàn)方式
這篇文章主要介紹了使用python實(shí)現(xiàn)時間序列白噪聲檢驗(yàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

