先上图:pandas piviot_table cheet sheet
or:
先初略的了解透视图是用来干什么的,一句话:pivot_table 最大的意义便是将数据分组表示并进行聚合运算(结合上面的图来看)。如果你了解pandas的 groupby ,那你会发现他们基本是相通的。
下面是正片:
pivot_table的参数理解
Signature:
pd.pivot_table(
data,
values=None,
index=None,
columns=None,
aggfunc='mean',
fill_value=None,
margins=False,
dropna=True,
margins_name='All',
observed=False,
)
Docstring:
Create a spreadsheet-style pivot table as a DataFrame. The levels in
the pivot table will be stored in MultiIndex objects (hierarchical
indexes) on the index and columns of the result DataFrame.
文档中已经说明,pd.pivot_table
会生成一个类型为DataFrame
的透视表。同时,表中的数据会以多索引和多列的结果表现在这个DataFrame中。
pivot_table 中四个最重要的参数是 index、values、columns、aggfunc:
-
data:DataFrame 格式
-
values:column to aggregate, optional,用来聚合计算的列(可选),也即对我们需要的数据进行筛选
-
index: Keys to group by on the pivot table index,按照行索引来分组的对象,每个pivot_table 必须拥有一个index,还可以用列表传入多个,形成多层索引
-
columns: Keys to group by on the pivot table column,按照列索引来分组的的对象,可以用列表传入多个,形成类似index的多层次字段,是非必要参数
-
aggfunc:用来聚合计算的函数,默认
aggfunc='mean'
。还可以以字典的方式,为不同的列分别自定义不同的聚合函数 -
fill_value:Value to replace missing values with,用来替换缺失值的值,默认为None
-
margins:Add all row / columns,添加分项小计,即添加标签为ALL的行和列
pivot 与 groupby
pd.pivot_table(df,index=[字段1],values=[字段2],aggfunc=[函数],fill_value=0)
df.groupby([字段1])[字段2].agg(函数).fillna(0)
上面两个函数完全等价,pivot_table仿佛是加入了columns与margin功能的groupby函数,比groupby更加灵活。
其它
查看
可以使用table.query()
去表格中查找某一项数据:
参考:
table.query('对手 == ["灰熊"]')
可视化
参考:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
# 使用Seaborn
sns.set()
pd.pivot_table(data, index= 'Region', columns= 'Year', values= "Happiness Score").plot(kind= 'bar')
plt.ylabel("Happiness Rank")
保存
参考:
save_file = "./titanic_analysis.xlsx"
with pd.ExcelWriter(save_file) as writer:
table.to_excel(writer, sheet_name='汇总-演示', encoding="utf-8")
table1.to_excel(writer, sheet_name='自定义聚合函数-演示', encoding="utf-8")
参考: