對(duì)數(shù)據(jù)進(jìn)行分組運(yùn)算是數(shù)據(jù)分析中很常見(jiàn)的操作胁赢,如果數(shù)據(jù)存儲(chǔ)在數(shù)據(jù)庫(kù)智末,如 MySQL、Oracle系馆、Hive 中虚青,那么使用 groupby 關(guān)鍵字在大部分時(shí)候就可以滿足需求棒厘。
Pandas 提供了一系列函數(shù)來(lái)實(shí)現(xiàn)類(lèi) SQL 語(yǔ)句奢人,好用到爆,下面來(lái)一起看看和 SQL 具體對(duì)應(yīng)的操作:
- select [column1, column2 ... ] where [condition1, condition2 ... ]
最基本的 select 操作句惯,其實(shí)在前面的電影篩選中已經(jīng)介紹過(guò)了,比如:
# 篩選電影排名小于等于 5 且評(píng)分高于 9.0
print movie_pd[ (movie_pd['rank'] <=5) & (movie_pd['score'] > 9.0) ]
# 篩選電影發(fā)布日期大于 2010-01-01 或 評(píng)論數(shù)超過(guò) 50萬(wàn)
print movie_pd[ (movie_pd['release_date'] > '2010-01-01') | (movie_pd['vote_count'] > 500000) ]
# 篩選電影鏈接為空的前 10 條
print movie_pd[ movie_pd['url'].isnull() ].head(10)
其中 &拷淘、| 符號(hào)分別相當(dāng)于 MySQL 中的 and启涯、or 操作符恃轩。
- groupby:分組運(yùn)算函數(shù)
按照電影類(lèi)型 category 分組計(jì)算每個(gè)類(lèi)型的電影個(gè)數(shù),SQL 如下:
select category, count(*) as num
from movie
group by category
對(duì)應(yīng)的 Pandas 操作:
import pandas as pd
import numpy as np
movie_pd = pd.read_csv('douban_movie.csv', header=0, sep='\t')
movie_pd.groupby('category').size()
部分輸出如下:
category
傳記 70
兒童 16
冒險(xiǎn) 155
劇情 534
其類(lèi)型為 Series松忍,如果想要轉(zhuǎn)化為 DataFrame 格式鸣峭,同時(shí)給電影個(gè)數(shù)那一列添加列名 num叽掘,可以使用 reset_index( ) 函數(shù),寫(xiě)法如下:
movie_pd.groupby('category').size().reset_index(name = 'num')
這樣輸出的就是標(biāo)準(zhǔn)的 DataFrame 格式了玖雁,方便之后的其他計(jì)算。
category num
0 傳記 70
1 兒童 16
2 冒險(xiǎn) 155
3 劇情 534
4 動(dòng)作 253
有時(shí)候盖腕,SQL 中還會(huì)涉及到 count ( distinct movie_id ) 的去重計(jì)數(shù)操作赫冬,這個(gè)時(shí)候把 size( ) 函數(shù)替換為 nunique( ) 函數(shù)即可,如下:
movie_pd.groupby('category')['movie_id'].nunique().reset_index(name='num')
- agg:輔助分組的函數(shù)
有時(shí)候按照某個(gè)字段分組以后溃列,需要計(jì)算多個(gè)字段的值劲厌,這個(gè)時(shí)候就可以借助 agg 函數(shù)來(lái)實(shí)現(xiàn)。
select id,
max(score) as max_score,
min(score) as min_score,
avg(vote_count) as avg_count
from movie
group by id
對(duì)應(yīng)的 Pandas 操作:
agg_pd = movie_pd.groupby('id').agg({
'score': [ np.max, np.min ], 'vote_count': np.mean
}).reset_index()
部分輸出如下:
id vote_count score
mean amax amin
0 1291543 265547.0 7.9 7.9
1 1291545 247248.0 8.7 8.7
2 1291546 629403.0 9.5 9.5
3 1291548 274956.0 8.9 8.9
4 1291549 453695.0 9.2 9.2
雖然以上是 DataFrame 格式听隐,但是列名看起來(lái)有點(diǎn)奇怪补鼻,輸出一下看看:
print(agg_pd.columns)
for temp in agg_pd.columns:
print(temp)
結(jié)果如下:
MultiIndex(levels=[[u'vote_count', u'score', u'id'], [u'amax', u'amin', u'mean', u'']], labels=[[2, 0, 1, 1], [3, 2, 0, 1]])
('id', '')
('vote_count', 'mean')
('score', 'amax')
('score', 'amin')
是一個(gè)復(fù)合索引,單獨(dú)來(lái)看的話雅任,每個(gè)列名都是一個(gè)元組风范,接下來(lái)對(duì)列名重命名硼婿,元組的元素之間用下劃線連接:
agg_pd.columns = agg_pd.columns.map('_'.join)
print(app_pd.head())
輸出如下:
id_ vote_count_mean score_amax score_amin
0 1291543 265547.0 7.9 7.9
1 1291545 247248.0 8.7 8.7
2 1291546 629403.0 9.5 9.5
3 1291548 274956.0 8.9 8.9
4 1291549 453695.0 9.2 9.2
id 后面也會(huì)有一個(gè)下劃線,不夠美觀记焊,所以也可以這么處理,如果元組的第二個(gè)元素為空就不加下劃線:
agg_pd.columns = ['%s%s' % (a, '_%s' % b if b else '') for a, b in agg_pd.columns]
print(agg_pd.head())
當(dāng)然也可以實(shí)現(xiàn)多字段分組捌归,比如:
select category, id,
avg(score) as avg_score,
max(vote_count) as max_count
from movie
group by category, id
對(duì)應(yīng)的 Pandas 操作如下:
print movie_pd.groupby(['category', 'id']).agg({
'score': np.mean, 'vote_count': np.max
}).reset_index()
如果需要對(duì)分組結(jié)果進(jìn)行排序的話剃浇,使用 sort_values( ) 函數(shù)
比如按照 score 降序排列,可以寫(xiě)成:
print movie_pd.groupby(['category', 'id']).agg({
'score': np.mean, 'vote_count': np.mean
}).reset_index().sort_values('score', ascending = False)
劃重點(diǎn)
- groupby( ) 分組運(yùn)算
- reset_index( ) 重置索引并可以更改列名
- agg( ) 輔助多字段分組
- sort_values( ) 按照字段排序