透视表
pivot_table
是各种电子表格和其他数据分析软件中一种常见的数据分析汇总工具。
- 根据一个或者多个键对数据进行聚合
- 根据行和列上的分组键将数据分配到各个矩形区域中
Pivot_table
特点
- 灵活性高,可以随意定制你的分析计算要求
- 脉络清晰易于理解数据
- 操作性强,报表神器
参数
data
: a DataFrame object,要应用透视表的数据框values
: a column or a list of columns to aggregate,要聚合的列,相当于“值”index
: a column, Grouper, array which has the same length as data, or list of them. Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values,聚合值的分组,相当于“行”columns
: a column, Grouper, array which has the same length as data, or list of them. Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values,聚合值的分组,相当于是"列"aggfunc
: function to use for aggregation, defaulting tonumpy.mean
,要应用的聚合函数,默认函数是均值
三个非常用参数
- fill_value : 有时候聚合结果里出现了
NaN
,想替换成0
时,fill_value=0; - dropna=True:是跳过整行都是空缺值的行
- margins : 是否添加所有行或列的小计/总计,margins=True;
- margins_name : 当margins设置为True时,设置总计的名称,默认是“ALL”。
demo
1 | In [1]: import datetime |
关于pivot_table
函数结果的说明:
df
是需要进行透视表的数据框values
是生成的透视表中的数据index
是透视表的层次化索引,多个属性使用列表的形式columns
是生成透视表的列属性
Crosstab
一种用于计算分组频率的特殊透视表。
1 | # 关于小费的栗子 |