Pandas使用stack和pivot實(shí)現(xiàn)數(shù)據(jù)透視的方法
筆者最近正在學(xué)習(xí)Pandas數(shù)據(jù)分析,將自己的學(xué)習(xí)筆記做成一套系列文章。本節(jié)主要記錄Pandas中使用stack和pivot實(shí)現(xiàn)數(shù)據(jù)透視。
一、經(jīng)過統(tǒng)計(jì)得到多維度指標(biāo)數(shù)據(jù)
非常場景的統(tǒng)計(jì)場景,指定多個(gè)維度,計(jì)算聚合后的指標(biāo)
實(shí)例:統(tǒng)計(jì)得到“電影評分?jǐn)?shù)據(jù)集”,每個(gè)月份的每個(gè)分?jǐn)?shù)被評分多少次:(月份、分?jǐn)?shù)1-5、次數(shù))
import pandas as pd import numpy as np %matplotlib inline df=pd.read_csv( "./datas/ml-1m/ratings.dat", sep="::", engine='python', names='UserID::MovieID::Rating::Timestamp'.split("::"), header=None ) df.head() #將時(shí)間戳轉(zhuǎn)換為具體的時(shí)間 df['padate']=pd.to_datetime(df["Timestamp"],unit='s') df.head() df.dtypes #實(shí)現(xiàn)數(shù)據(jù)統(tǒng)計(jì) # 對于這樣格式的數(shù)據(jù),我想查看按月份,不同評分的次數(shù)趨勢,是沒有辦法進(jìn)行實(shí)現(xiàn)的,需要將數(shù)據(jù)轉(zhuǎn)換為每個(gè)評分是一列才可以實(shí)現(xiàn)。 df_group=df.groupby([df["padate"].dt.month,"Rating"])["UserID"].agg(pv=np.sum) df_group.head(20)
二、使用unstack實(shí)現(xiàn)數(shù)據(jù)的二維透視
目的: 想要畫圖對比按照月份的不同評分的數(shù)量趨勢
df_stack=df_group.unstack() df_stack df_stack.plot() #unstack和stack是互逆的操作 df_stack.stack().head(20)
三、使用pivot簡化透視
pivot方法相當(dāng)于對df使用set_index創(chuàng)建分層索引,然后調(diào)用unstack
df_group.head(20) df_reset=df_group.reset_index() df_reset.head() df_pivot=df_reset.pivot("padate","Rating","pv") df_pivot.head() df_pivot.plot()
四、stack、unstack、pivot的語法
1.stack
stack:DataFrame.stack(level=-1,dropna=True),將column變成index,類似把橫放的書籍變成豎放
level=-1代表多層索引的最內(nèi)層,可以通過==0,1,2指定多層索引的對應(yīng)層
2.unstack
unstack:DataFrame.unstack(level=-1,fill_value=None),將index變成column,類似把豎放的書變成橫放
3.pivot
pivot:DataFrame.pivot(index=None,columns=None,values=None),指定index,columns,values實(shí)現(xiàn)二維透視
總結(jié)
到此這篇關(guān)于Pandas使用stack和pivot實(shí)現(xiàn)數(shù)據(jù)透視的方法的文章就介紹到這了,更多相關(guān)Pandas stack和pivot數(shù)據(jù)透視內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。