Excel高級功能還是不太懂,如數據透視表、函數等。 在數據處理方面, 既然Excel能做的,那當然Python的pandas應該也能完成。總結下Pandas是如何完成數據透視表和交叉表的。
-
數據透視表
數據透視表是一種常見的數據匯總工具,根據一個或者多個鍵對數據進行聚合,並根據行、列分組將數據分配到各個矩形區域。pandas.DataFrame中含有pivot_table方法、pandas.pivot_table來實現數據透視表。
pandas.DataFrame.pivot_table函數參數:
pivot_table(self, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All')
# values :
合並的列,需要聚合的列
# index
: 要聚合的列
# columns : 用與分組的列名,可以理解為列索引名
# aggfunc : 聚合函數
# fill_value: 缺失值填充
# dropna : boolean, default = True, 當前列都為NaN時,整列丟棄。
# margins: boolean, default = False , 當margins=True, 增加列/行總計
# margins_name string , default = 'All', 設定margin列名
我選用的是fifa19的數據集, 從多個列中挑選了7個列,且排除了評分75以下的球員
import numpy as np
import pandas as pd
fifa_df = pd.read_csv('data.csv')
fifa_df.shape # 源數據維度(18207, 89)
selected_data = fifa_df[[u'ID',u'Name', u'Age',u'Nationality',u'Club',u'Potential',u'Overall']]
selected_data = selected_data[selected_data[u'Overall'] > 75] # 評分75以上球員
selected_data.head() # 查看數據前幾行
用Club篩選球員
selected_data.pivot_table(index= [u'Club']) # aggfunc 默認是 aggfunc='mean', 所以求的是均值
Club 和 Nationality 篩選
selected_data.pivot_table(index= [u'Nationality', u'Club'])
我想看具體球員名稱, 就要在index中添加 u‘Name’, 查看阿根廷球員在哪些俱樂部
selected_data.pivot_table(index= [u'Nationality', u'Club', u'Name'])
selected_data.pivot_table(index= [u'Nationality', u'Club', u'Name']).loc['Argentina']
下圖來解釋 pivot_table 函數參數的位置關系
- query查詢分析
我已經生成了數據透視表, 我要查看拉齊奧有哪些球員,如何查詢呢?
table = selected_data.pivot_table(index= [u'Nationality', u'Club', u'Name'], values=[u'Age', u'Overall', u'Potential'])
table.query('Club==["Lazio"]')
- 交叉表
交叉表是一種特殊的pivot_table, 同於統計分組頻率。
文檔里的crosstab函數如下:
crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name='All', dropna=True, normalize=False)
# index : 行索引
# columns: 列值
# value : 聚合的值
# rownames、colnames: 行、列名
# aggfunc: 聚合函數
# normalize : 正則化
- If passed 'all' or `True`, will normalize over all values.
- If passed 'index' will normalize over each row.
- If passed 'columns' will normalize over each column.
- If margins is `True`, will also normalize margin values.
我要看某個國家在各個俱樂部的分布, 比如看阿根廷在各個俱樂部有幾名球員
cross_tables_fifa = pd.crosstab(index=selected_data[u'Nationality'], columns=selected_data[u'Club'] )
cross_tables_fifa.query('Nationality==["Argentina"]')