pandas系列学习(七):数据透视表 您所在的位置:网站首页 怎么做透视表 pandas系列学习(七):数据透视表

pandas系列学习(七):数据透视表

2024-01-22 07:09| 来源: 网络整理| 查看: 265

作者:chen_h 微信号 & QQ:862251340 微信公众号:coderpai

pandas系列学习(一):pandas入门

pandas系列学习(二):Series

pandas系列学习(三):DataFrame

pandas系列学习(四):数据提取

pandas系列学习(五):数据连接

pandas系列学习(六):数据聚合

pandas系列学习(七):数据透视表

介绍

大多数人可能都有使用 Excel 中的数据透视表的经验。 pandas 提供了一个类似的功能,称为 pivot_table。虽然它非常有用,但我经常发现自己很难记住如何使用语法格式化输出以满足我的需求。本文将重点介绍 pandas pivot_table 函数以及如何将其用于数据分析。

作为一个额外的奖励,我创建了一个简单的备忘录,总结了 pivot_table 。你可以在这篇文章的最后找到它,我希望它是一个有用的参考。

数据

使用 pandas 的 pivot_table 的一个挑战是确保你了解你的数据以及你尝试使用数据透视表来处理问题。这是一个看似简单的功能,但可以非常快速的产生非常强大的分析。

在这种情况下,我将跟踪销售渠道(也称为渠道)。基本问题是一些销售周期很长,管理层希望全年更详细的了解它。

典型问题包括:

管道中有多少收入?什么产品正在筹备中?谁在什么阶段有什么产品?我们有多大可能在年底前完成交易?

许多公司将拥有销售用于跟踪流程的 CRM 工具或其他软件。虽然他们可能有分析数据的有用工具,但不可避免的有人会将数据导出到 Excel 并使用数据透视表来汇总数据。

使用 padnas 的数据透视表可能是一个很好的选择,因为它是:

更快(一旦设置)自我记录(查看代码,你知道它做了什么)易于使用生成报告或者电子邮件更灵活,因为你可以定义客户关心的内容 读入数据

让我们先建立我们的环境,数据你可以点击这个下载。然后将我们的销售数据读入 DataFrame ,如下:

import pandas as pd import numpy as np df = pd.read_excel("./sales-funnel.xlsx") df.head() AccountNameRepManagerProductQuantityPriceStatus0714466Trantow-BarrowsCraig BookerDebra HenleyCPU130000presented1714466Trantow-BarrowsCraig BookerDebra HenleySoftware110000presented2714466Trantow-BarrowsCraig BookerDebra HenleyMaintenance25000pending3737550Fritsch, Russel and AndersonCraig BookerDebra HenleyCPU135000declined4146832Kiehn-SpinkaDaniel HiltonDebra HenleyCPU265000won

为了方便起见,我们将状态列定义为类别并设置我们要查看的顺序。

这不是严格要求的,但可以帮助我们在分析数据时保持我们想要的顺序。

df["Status"] = df["Status"].astype("category") df["Status"].cat.set_categories(["won","pending","presented","declined"],inplace=True) 透视数据

在我们构建数据透视表时,我认为最简单的方法就是一步一步。添加项目并检查每个步骤以验证你是否获得了预期的结果。不要害怕使用订单和变量来查看哪些需求。

最简单的数据透视表必须具有数据框和索引。在这种情况下,让我们使用 Name 作为索引。

pd.pivot_table(df,index=["Name"]) AccountPriceQuantityNameBarton LLC740150.035000.01.000000Fritsch, Russel and Anderson737550.035000.01.000000Herman LLC141962.065000.02.000000Jerde-Hilpert412290.05000.02.000000Kassulke, Ondricka and Metz307599.07000.03.000000Keeling LLC688981.0100000.05.000000Kiehn-Spinka146832.065000.02.000000Koepp Ltd729833.035000.02.000000Kulas Inc218895.025000.01.500000Purdy-Kunde163416.030000.01.000000Stokes LLC239344.07500.01.000000Trantow-Barrows714466.015000.01.333333

你也可以拥有多个索引。是加上,大多数的 pivot_table args 都可以通过列表获取多个值。

pd.pivot_table(df,index=["Name","Rep","Manager"]) AccountPriceQuantityNameRepManagerBarton LLCJohn SmithDebra Henley740150.035000.01.000000Fritsch, Russel and AndersonCraig BookerDebra Henley737550.035000.01.000000Herman LLCCedric MossFred Anderson141962.065000.02.000000Jerde-HilpertJohn SmithDebra Henley412290.05000.02.000000Kassulke, Ondricka and MetzWendy YuleFred Anderson307599.07000.03.000000Keeling LLCWendy YuleFred Anderson688981.0100000.05.000000Kiehn-SpinkaDaniel HiltonDebra Henley146832.065000.02.000000Koepp LtdWendy YuleFred Anderson729833.035000.02.000000Kulas IncDaniel HiltonDebra Henley218895.025000.01.500000Purdy-KundeCedric MossFred Anderson163416.030000.01.000000Stokes LLCCedric MossFred Anderson239344.07500.01.000000Trantow-BarrowsCraig BookerDebra Henley714466.015000.01.333333

这很有趣但不是特别有用。我们可能想要做的是通过 Manager 和 Rep 查看。通过更改索引可以轻松完成。

pd.pivot_table(df,index=["Manager","Rep"]) AccountPriceQuantityManagerRepDebra HenleyCraig Booker720237.020000.0000001.250000Daniel Hilton194874.038333.3333331.666667John Smith576220.020000.0000001.500000Fred AndersonCedric Moss196016.527500.0000001.250000Wendy Yule614061.544250.0000003.000000

你可以看到数据透视表非常智能,可以通过将 reps 与 manager 分组来开始汇总数据并对其进行汇总。现在我们开始了解数据透视表可以为我们做些什么。

为此,“账户” 和 “数量” 列不真正有用。让我们通过使用 values 字段显式定义我们关心的列来删除它。

pd.pivot_table(df,index=["Manager","Rep"],values=["Price"]) PriceManagerRepDebra HenleyCraig Booker20000.000000Daniel Hilton38333.333333John Smith20000.000000Fred AndersonCedric Moss27500.000000Wendy Yule44250.000000

价格列自动平均数据,但我们可以进行计数或者总和。使用 aggfunc 和 np.sum 添加它们很简单。

pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],aggfunc=np.sum) PriceManagerRepDebra HenleyCraig Booker80000Daniel Hilton115000John Smith40000Fred AndersonCedric Moss110000Wendy Yule177000

aggfunc 可以获取一系列函数。让我们尝试使用 np.mean 函数和 len 来计算。

pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],aggfunc=[np.mean,len]) meanlenPricePriceManagerRepDebra HenleyCraig Booker20000.0000004Daniel Hilton38333.3333333John Smith20000.0000002Fred AndersonCedric Moss27500.0000004Wendy Yule44250.0000004

如果我们想要查看按产品细分的销售额,则 columns 变量允许我们定义一个或者多格列。

我认为 pivot_table 的一个令人困惑的问题是使用列和值。请记住,列是可选的 —— 它们提供了一种额外的方法来细分你关心的实际值。聚合函数将应用于你列出的值。

pd.pivot_table(df,index=["Manager","Rep"],values=["Price"], columns=["Product"],aggfunc=[np.sum]) sumPriceProductCPUMaintenanceMonitorSoftwareManagerRepDebra HenleyCraig Booker65000.05000.0NaN10000.0Daniel Hilton105000.0NaNNaN10000.0John Smith35000.05000.0NaNNaNFred AndersonCedric Moss95000.05000.0NaN10000.0Wendy Yule165000.07000.05000.0NaN

NaN 有点让人抓狂。如果我们想要删除它们,我们可以使用 fill_value 将它们设置为 0 。

pd.pivot_table(df,index=["Manager","Rep"],values=["Price"], columns=["Product"],aggfunc=[np.sum],fill_value=0) sumPriceProductCPUMaintenanceMonitorSoftwareManagerRepDebra HenleyCraig Booker650005000010000Daniel Hilton1050000010000John Smith35000500000Fred AndersonCedric Moss950005000010000Wendy Yule165000700050000

我认为添加数量列也是非常有用的,将数量添加到值列表中。

pd.pivot_table(df,index=["Manager","Rep"],values=["Price","Quantity"], columns=["Product"],aggfunc=[np.sum],fill_value=0) sumPriceQuantityProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareManagerRepDebra HenleyCraig Booker6500050000100002201Daniel Hilton10500000100004001John Smith350005000001200Fred AndersonCedric Moss9500050000100003101Wendy Yule1650007000500007320

有趣的是,你可以将项目移动到索引以获得不同的可视化结果。从列中删除产品并添加都索引中。

pd.pivot_table(df,index=["Manager","Rep","Product"], values=["Price","Quantity"],aggfunc=[np.sum],fill_value=0) sumPriceQuantityManagerRepProductDebra HenleyCraig BookerCPU650002Maintenance50002Software100001Daniel HiltonCPU1050004Software100001John SmithCPU350001Maintenance50002Fred AndersonCedric MossCPU950003Maintenance50001Software100001Wendy YuleCPU1650007Maintenance70003Monitor50002

对于此数据集,此表示更有意义。现在,如果我想看一些总数怎么办?marginins = True 可以帮助我们实现。

pd.pivot_table(df,index=["Manager","Rep","Product"], values=["Price","Quantity"], aggfunc=[np.sum,np.mean],fill_value=0,margins=True) summeanPriceQuantityPriceQuantityManagerRepProductDebra HenleyCraig BookerCPU650002325001.000000Maintenance5000250002.000000Software100001100001.000000Daniel HiltonCPU1050004525002.000000Software100001100001.000000John SmithCPU350001350001.000000Maintenance5000250002.000000Fred AndersonCedric MossCPU950003475001.500000Maintenance5000150001.000000Software100001100001.000000Wendy YuleCPU1650007825003.500000Maintenance7000370003.000000Monitor5000250002.000000All52200030307051.764706

让我们将分析提升到一个水平,并在 manager 级别查看我们的数据管道。请注意如何根据我们之前的类别定义对状态进行排序。

pd.pivot_table(df,index=["Manager","Status"],values=["Price"], aggfunc=[np.sum],fill_value=0,margins=True) sumPriceManagerStatusDebra Henleywon65000pending50000presented50000declined70000Fred Andersonwon172000pending5000presented45000declined65000All522000

一个非常方便的功能是能够将字典传递给 aggfunc,因此你可以对你选择的每个值执行不同的功能。这具有使标签更清洁的作用。

pd.pivot_table(df,index=["Manager","Status"],columns=["Product"],values=["Quantity","Price"], aggfunc={"Quantity":len,"Price":np.sum},fill_value=0) PriceQuantityProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareManagerStatusDebra Henleywon650000001000pending4000010000001200presented3000000200001002declined700000002000Fred Andersonwon1650007000002100pending05000000100presented3000005000100001011declined650000001000

你也可以提供要应用于每个值的聚合函数列表:

table = pd.pivot_table(df,index=["Manager","Status"],columns=["Product"],values=["Quantity","Price"], aggfunc={"Quantity":len,"Price":[np.sum,np.mean]},fill_value=0) table PriceQuantitymeansumlenProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareManagerStatusDebra Henleywon65000000650000001000pending400005000004000010000001200presented3000000100003000000200001002declined35000000700000002000Fred Andersonwon825007000001650007000002100pending050000005000000100presented3000005000100003000005000100001011declined65000000650000001000

尝试将这一切全部拉到一起可能看起来非常疯狂,但是一旦你开始玩数据并慢慢添加项目,你就可以了解它是如何工作的。我的一般经验法则是,一旦你使用多个 group,你应该评估一个数据透视表是否是一个有用的方法。

高级数据透视表过滤

生成数据后,它就位于 DataFrame 中,因此你可以使用标准 DataFrame 函数对其进行过滤。

如果你只想看一个 manager:

table.query('Manager == ["Debra Henley"]') PriceQuantitymeansumlenProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareManagerStatusDebra Henleywon65000000650000001000pending400005000004000010000001200presented3000000100003000000200001002declined35000000700000002000

我们可以查看所有待处理和赢得的交易。

table.query('Status == ["pending","won"]') PriceQuantitymeansumlenProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareManagerStatusDebra Henleywon65000000650000001000pending400005000004000010000001200Fred Andersonwon825007000001650007000002100pending050000005000000100

这是 pivot_table 的强大功能,所以一旦你将数据转换为你需要的 pivot_table 格式,请不要忘记你拥有一个强大的功能。

为了总结所有这些,我创建了一个被王丹,希望能帮助你记住 pandas pivot_table 的使用方法,如下:

在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有