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

作者: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()
AccountNameRepManagerProductQuantityPriceStatus
0714466Trantow-BarrowsCraig BookerDebra HenleyCPU130000presented
1714466Trantow-BarrowsCraig BookerDebra HenleySoftware110000presented
2714466Trantow-BarrowsCraig BookerDebra HenleyMaintenance25000pending
3737550Fritsch, Russel and AndersonCraig BookerDebra HenleyCPU135000declined
4146832Kiehn-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"])
AccountPriceQuantity
Name
Barton LLC740150.035000.01.000000
Fritsch, Russel and Anderson737550.035000.01.000000
Herman LLC141962.065000.02.000000
Jerde-Hilpert412290.05000.02.000000
Kassulke, Ondricka and Metz307599.07000.03.000000
Keeling LLC688981.0100000.05.000000
Kiehn-Spinka146832.065000.02.000000
Koepp Ltd729833.035000.02.000000
Kulas Inc218895.025000.01.500000
Purdy-Kunde163416.030000.01.000000
Stokes LLC239344.07500.01.000000
Trantow-Barrows714466.015000.01.333333

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

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

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

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

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

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

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

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

pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],aggfunc=np.sum)
Price
ManagerRep
Debra HenleyCraig Booker80000
Daniel Hilton115000
John Smith40000
Fred AndersonCedric Moss110000
Wendy Yule177000

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

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

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

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

pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],
               columns=["Product"],aggfunc=[np.sum])
sum
Price
ProductCPUMaintenanceMonitorSoftware
ManagerRep
Debra HenleyCraig Booker65000.05000.0NaN10000.0
Daniel Hilton105000.0NaNNaN10000.0
John Smith35000.05000.0NaNNaN
Fred AndersonCedric Moss95000.05000.0NaN10000.0
Wendy 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)
sum
Price
ProductCPUMaintenanceMonitorSoftware
ManagerRep
Debra HenleyCraig Booker650005000010000
Daniel Hilton1050000010000
John Smith35000500000
Fred AndersonCedric Moss950005000010000
Wendy Yule165000700050000

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

pd.pivot_table(df,index=["Manager","Rep"],values=["Price","Quantity"],
               columns=["Product"],aggfunc=[np.sum],fill_value=0)
sum
PriceQuantity
ProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftware
ManagerRep
Debra HenleyCraig Booker6500050000100002201
Daniel Hilton10500000100004001
John Smith350005000001200
Fred AndersonCedric Moss9500050000100003101
Wendy Yule1650007000500007320

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

pd.pivot_table(df,index=["Manager","Rep","Product"],
               values=["Price","Quantity"],aggfunc=[np.sum],fill_value=0)
sum
PriceQuantity
ManagerRepProduct
Debra HenleyCraig BookerCPU650002
Maintenance50002
Software100001
Daniel HiltonCPU1050004
Software100001
John SmithCPU350001
Maintenance50002
Fred AndersonCedric MossCPU950003
Maintenance50001
Software100001
Wendy YuleCPU1650007
Maintenance70003
Monitor50002

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

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

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

pd.pivot_table(df,index=["Manager","Status"],values=["Price"],
               aggfunc=[np.sum],fill_value=0,margins=True)
sum
Price
ManagerStatus
Debra Henleywon65000
pending50000
presented50000
declined70000
Fred Andersonwon172000
pending5000
presented45000
declined65000
All522000

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

pd.pivot_table(df,index=["Manager","Status"],columns=["Product"],values=["Quantity","Price"],
               aggfunc={"Quantity":len,"Price":np.sum},fill_value=0)
PriceQuantity
ProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftware
ManagerStatus
Debra Henleywon650000001000
pending4000010000001200
presented3000000200001002
declined700000002000
Fred Andersonwon1650007000002100
pending05000000100
presented3000005000100001011
declined650000001000

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

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
PriceQuantity
meansumlen
ProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftware
ManagerStatus
Debra Henleywon65000000650000001000
pending400005000004000010000001200
presented3000000100003000000200001002
declined35000000700000002000
Fred Andersonwon825007000001650007000002100
pending050000005000000100
presented3000005000100003000005000100001011
declined65000000650000001000

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

高级数据透视表过滤

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

如果你只想看一个 manager:

table.query('Manager == ["Debra Henley"]')
PriceQuantity
meansumlen
ProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftware
ManagerStatus
Debra Henleywon65000000650000001000
pending400005000004000010000001200
presented3000000100003000000200001002
declined35000000700000002000

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

table.query('Status == ["pending","won"]')
PriceQuantity
meansumlen
ProductCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftwareCPUMaintenanceMonitorSoftware
ManagerStatus
Debra Henleywon65000000650000001000
pending400005000004000010000001200
Fred Andersonwon825007000001650007000002100
pending050000005000000100

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

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

在这里插入图片描述

  • 21
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Pandas是一个强大的数据分析工具,它提供了丰富的功能来处理和分析数据。其中之一就是数据透视表(Pivot Table)的功能。 数据透视表是一种用于对数据进行汇总和分析的技术,它可以根据一个或多个字段对数据进行分组,并计算其他字段的统计指标(如求和、平均值等)。在Pandas中,可以使用`pivot_table()`函数来创建数据透视表。 下面是一个简单的示例代码,展示了如何使用Pandas创建数据透视表: ```python import pandas as pd # 创建一个示例数据集 data = { 'Name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob', 'Charlie'], 'City': ['New York', 'London', 'Paris', 'New York', 'London', 'Paris'], 'Sales': [100, 200, 150, 300, 250, 200] } df = pd.DataFrame(data) # 创建数据透视表 pivot_table = df.pivot_table(values='Sales', index='Name', columns='City', aggfunc='sum') # 打印数据透视表 print(pivot_table) ``` 在上述代码中,我们首先创建了一个包含姓名、城市和销售额的示例数据集。然后,使用`pivot_table()`函数创建了一个数据透视表,其中`values`参数指定了要计算统计指标的字段(这里是销售额),`index`参数指定了分组的字段(这里是姓名),`columns`参数指定了列的字段(这里是城市),`aggfunc`参数指定了要计算的统计指标(这里是求和)。 最后,通过打印数据透视表,我们可以看到按照姓名和城市进行分组后的销售额统计结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值