阿里媽媽 網(wǎng)站建設(shè)不完整長(zhǎng)沙網(wǎng)絡(luò)優(yōu)化產(chǎn)品
Pandas——groupby操作
文章目錄
- Pandas——groupby操作
- 一、實(shí)驗(yàn)?zāi)康?/li>
- 二、實(shí)驗(yàn)原理
- 三、實(shí)驗(yàn)環(huán)境
- 四、實(shí)驗(yàn)內(nèi)容
- 五、實(shí)驗(yàn)步驟
一、實(shí)驗(yàn)?zāi)康?/h1>
熟練掌握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ù)索引級(jí)別分組
sort:對(duì)groupby分組后新的dataframe中索引進(jìn)行排序,sort=True為升序,
as_index:在groupby中使用的鍵是否成為新的dataframe中的索引,默認(rèn)as_index=True
group_keys:在調(diào)用apply時(shí),將group鍵添加到索引中以識(shí)別片段
squeeze :如果可能的話,減少返回類型的維數(shù),否則返回一個(gè)一致的類型
grouping操作(split-apply-combine)
數(shù)據(jù)的分組&聚合 – 什么是groupby 技術(shù)?
在數(shù)據(jù)分析中,我們往往需要在將數(shù)據(jù)拆分,在每一個(gè)特定的組里進(jìn)行運(yùn)算。比如根據(jù)教育水平和年齡段計(jì)算某個(gè)城市的工作人口的平均收入。
pandas中的groupby提供了一個(gè)高效的數(shù)據(jù)的分組運(yùn)算。
我們通過一個(gè)或者多個(gè)分類變量將數(shù)據(jù)拆分,然后分別在拆分以后的數(shù)據(jù)上進(jìn)行需要的計(jì)算
我們可以把上述過程理解為三部:
1.拆分?jǐn)?shù)據(jù)(split)
2.應(yīng)用某個(gè)函數(shù)(apply)
3.匯總計(jì)算結(jié)果(aggregate)
下面這個(gè)演示圖展示了“分拆-應(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)建一個(gè)數(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列對(duì)df進(jìn)行分布操作。
df.groupby('A')
3.通過A、B列對(duì)df進(jìn)行分組操作。
df.groupby(['A','B'])
4…使用自定義函數(shù)進(jìn)行分組操作,自定義一個(gè)函數(shù),使用groupby方法并使用自定義函數(shù)給定的條件,按列對(duì)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)建一個(gè)Series名為s,使用groupby根據(jù)s的索引對(duì)s進(jìn)行分組,返回分組后的新Series,對(duì)新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()
#對(duì)分組的各組進(jìn)行求和
grouped.sum()
6.分組排序,使用groupby進(jìn)行分組時(shí),默認(rèn)是按分組后索引進(jìn)行升序排列,在groupby方法中加入sort=False參數(shù),可以進(jìn)行降序排列。
df2=pd.DataFrame({'X':['B','B','A','A'],'Y':[1,2,3,4]})
#按X列對(duì)df2進(jìn)行分組,并求每組的和
df2.groupby(['X']).sum()
#按X列對(duì)df2進(jìn)行分組,分組時(shí)不對(duì)鍵進(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.多級(jí)索引分組,創(chuàng)建一個(gè)有兩級(jí)索引的Series,并使用兩個(gè)方法對(duì)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ù)合分組,對(duì)s按first、second進(jìn)行分組并求和。
s.groupby(level=['first', 'second']).sum()
11.復(fù)合分組(按索引和列),創(chuàng)建數(shù)據(jù)幀df,使用索引級(jí)別和列對(duì)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.對(duì)df進(jìn)行分組,將分組后C列的值賦值給grouped,統(tǒng)計(jì)grouped中每類的個(gè)數(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.對(duì)上面創(chuàng)建的df的C列,按A列值進(jìn)行分組并求和。
df['C'].groupby(df['A']).sum()
14.遍歷分組結(jié)果,通過A,B兩列對(duì)df進(jìn)行分組,分組結(jié)果的組名為元組。
for name, group in df.groupby(['A', 'B']): print(name) print(group)
15.通過A列對(duì)df進(jìn)行分組,并查看分組對(duì)象的bar列。
df.groupby(['A']).get_group(('bar'))
16.按A,B兩列對(duì)df進(jìn)行分組,并查看分組對(duì)象中bar、one都存在的部分。
df.groupby(['A','B']).get_group(('bar','one'))
注意:當(dāng)分組按兩列來分時(shí),查看分組對(duì)象也應(yīng)該包含每列的一部分。
17.聚合操作,按A列對(duì)df進(jìn)行分組,使用聚合函數(shù)aggregate求每組的和。
grouped=df.groupby(['A'])
grouped.aggregate(np.sum)
按A、B兩列對(duì)df進(jìn)行分組,并使用聚合函數(shù)aggregate對(duì)每組求和。
grouped=df.groupby(['A','B'])
grouped.aggregate(np.sum)
注意:通過上面的結(jié)果可以看到。聚合完成后每組都有一個(gè)組名作為新的索引,使用as_index=False可以忽略組名。
18.當(dāng)as_index=True時(shí),在groupby中使用的鍵將成為新的dataframe中的索引。按A、B兩列對(duì)df進(jìn)行分組,這是使參數(shù)as_index=False,再使用聚合函數(shù)aggregate求每組的和.
grouped=df.groupby(['A','B'],as_index=False)
grouped.aggregate(np.sum)
19.聚合操作,按A、B列對(duì)df進(jìn)行分組,使用size方法,求每組的大小。返回一個(gè)Series,索引是組名,值是每組的大小。
grouped=df.groupby(['A','B'])
grouped.size()
20.聚合操作,對(duì)分組grouped進(jìn)行統(tǒng)計(jì)描述。
grouped.describe()
注意:聚合函數(shù)可以減少數(shù)據(jù)幀的維度,常用的聚合函數(shù)有:mean、sum、size、count、std、var、sem 、describe、first、last、nth、min、max。
執(zhí)行多個(gè)函數(shù)在一個(gè)分組結(jié)果上:在分組返回的Series中我們可以通過一個(gè)聚合函數(shù)的列表或一個(gè)字典去操作series,返回一個(gè)DataFrame。