一文了解python 透视图(pandas.pivot_table)

先上图: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")

参考:

  1. 玩转Pandas透视表
  2. Pandas | 一文看懂透视表pivot_table
  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值