- Python+Office:轻松实现Python办公自动化
- 王国平
- 724字
- 2025-02-18 05:44:24
3.7 数据的透视
透视表是各类数据分析软件中一种常见的数据汇总工具。它根据一个或多个键对数据进行聚合,并根据行和列上的分组键将数据分配到各个矩形区域中。本节将介绍利用pivot_table()函数和crosstab()函数进行数据透视。
3.7.1 pivot_table()函数:数据透视
在Python中,可以使用groupby()函数重塑运算制作透视表。此外在Pandas库中还有一个pivot_table()函数。
下面介绍一下Pandas库中pivot_table()函数的参数及其说明,如表3-1所示。
表3-1 pivot_table()函数的参数及其说明

续表

接下来,我们介绍下面程序使用的数据集。众所周知,在西方国家的服务行业中,顾客会给服务员一定金额的小费,这里我们使用餐饮行业的小费数据集,它包括消费总金额(totall_bill)、小费金额(tip)、顾客性别(sex)、消费的星期(day)、消费的时间段(time)、用餐人数(size)、顾客是否抽烟(smoker)等7个字段,如表3-2所示。
表3-2 顾客小费数据集

下面导入数据集,代码如下:

运行上述代码,输出结果如下所示。

例如,想要根据sex和smoker计算分组平均数,并将sex和smoker放到行上,代码如下:

运行上述代码,输出结果如下所示。

例如,想要聚合tip和size,而且需要根据sex和day进行分组,将smoker放到列上,把sex和day放到行上,代码如下:

运行上述代码,输出结果如下所示。

可以对这个表做进一步处理。例如,设置margins=True,添加加分小计,代码如下:

运行上述代码,输出结果如下所示。

如果想要使用其他的聚合函数,则将其传给参数aggfunc即可。例如,使用len可以得到有关分组大小的交叉表,代码如下:

运行上述代码,输出结果如下所示。

3.7.2 crosstab()函数:数据交叉
Pandas库中的crosstab()函数是一类用于计算分组频率的特殊透视表,也是一类特殊的pivot_table()函数。
例如,需要根据性别和是否吸烟对数据进行统计汇总,代码如下:

运行上述代码,输出结果如下所示。

例如,需要根据性别、星期和是否吸烟对数据进行统计汇总,代码如下:

运行上述代码,输出结果如下所示。
