Pandas透視表和交叉表

個人理解:透視表和交叉表都是可分組彙總表,透視表可以求平均值,求和等等,交叉表是透視表的一種,是計算分組頻數的

 

參考:《利用Python進行數據分析》

透視表
pivot_table的參數
交叉表crosstab
總結
透視表

透視表(pivot table)是各種電子表格程序和其他數據分析軟件中一種常見的數據彙總工具。它根據一個或多個鍵對數據進行聚合,並根據行和列上得分組建將數據分配到各個矩形區域中。在Python和pandas中,可以通過本章所介紹的groupby功能以及(能夠利用層次化索引的)重塑運算製作透視表。DataFrame有一個pivot_table方法,此外還有一個頂級的pandas.pivot_table函數。除了能爲groupby提供便利之外,pivot_table還可以添加分項小計(也叫margins)。
 
回到如上圖所示的小費數據集,假設我想要根據sex和smoker計算分組平均數(pivot_table的默認聚合類型),並將sex和smoker放到行上:

# 方法一:使用groupby
tips.groupby(['sex', 'smoker']).mean()
# 方法二:使用pivot_table
tips.pivot_table(row=['sex', 'smoker'])
1
2
3
4
結果是一樣的(嚴格來說,列的排列順序不一樣): 
 
現在假設我們只想聚合tip_pct和size,而且想根據day進行分組。我將smoker放到列上,把day放到行上:

tips.pivot_table(values=['tip_pct', 'size'], index=['sex', 'day'], columns='smoker')
1
 
可以看到,pivot_table()函數給我們提供了很多參數,用來選擇用那些數據創建透視表,以及調整創建透視表之後的行和列。 
還可以對這個表作進一步處理,傳入margins=True添加加分小計。這將會添加標籤爲ALL的行和列,其值對應於單個等級中所有數據的分組統計。在下面這個例子中,ALL值爲平均數:不單獨考慮菸民與非菸民(ALL列),不單獨考慮行分組兩個級別中的任何單項(ALL行)。換句話說:就是下面的ALL行和右邊的ALL列只統計對應的列和行。

tips.pivot_table(values=['tip_pct', 'size'], index=['sex', 'day'], columns='smoker', margins=True)
1
 
要使用其他的聚合函數,將其傳給參數aggfunc即可。例如,使用count或len可以得到有關分組大小的交叉表:

tips.pivot_table('tip_pct', index=['sex', 'smoker'], columns='day', aggfunc=len, margins=True)
1


pivot_table的參數

aggfunc : function or list of functions, default numpy.mean 
If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves) 
fill_value : scalar, default None 
Value to replace missing values with 
margins : boolean, default False 
Add all row / columns (e.g. for subtotal / grand totals)

parameters    introduction
data    DataFrame
values    待聚合的列的名稱。默認聚合所有數值列
index    用於分組的列名或其他分組鍵,出現在結果透視表的行
columns    用於分組的列名或其他分組鍵,出現在結果透視表的列
aggfunc    聚合函數或函數列表,默認爲‘mean’。可以使任何對groupby有效的函數
fill_value    用於替換結果表中的缺失值
dropna    boolean,默認爲True
margins_name    string,默認爲‘ALL’,當參數margins爲True時,ALL行和列的名字
交叉表:crosstab

交叉表(cross-tabulation, 簡稱crosstab)是一種用於計算分組頻率的特殊透視表。下面這個範例數據很典型,取自交叉表的Wikipedia頁:
data = pd.DataFrame({'Sample': range(1, 11), 'Gender': ['Female', 'Male', 'Female', 'Male', 'Male', 'Male', 'Female', 'Female', 'Male', 'Female'], 
                    'Handedness': ['Right-handed', 'Left-handed', 'Right-handed', 'Right-handed', 'Left-handed', 'Right-handed', 'Right-handed', 'Left-handed', 'Right-handed', 'Right-handed']})
1
2
 
假設我們想要根據性別和用手習慣對這段數據進行統計彙總。雖然可以用pivot_table()實現該功能,但是pandas.crosstab()函數會更方便:

# 方法一:用pivot_table
# 其實我覺的一點都不麻煩ε=(´ο`*)))唉
data.pivot_table(index=['Gender'], columns='Handedness', aggfunc=len, margins=True)
# 方法二:用crosstab
pd.crosstab(data.Gender, data.Handedness, margins=True)
1
2
3
4
5
 
可以看到,crosstab()的前兩個參數可以是數組、Series或數組列表。再比如對小費數據集:

pd.crosstab([tips.time, tips.day], tips.smoker, margins=True)
1


總結

透視表pivot_table()是一種進行分組統計的函數,參數aggfunc決定統計類型;
交叉表crosstab()是一種特殊的pivot_table(),專用於計算分組頻率(個人:應該理解爲分組頻數)。
--------------------- 
作者:hustqb 
來源:CSDN 
原文:https://blog.csdn.net/hustqb/article/details/78086394 
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章