python - 使用 pivot_table 和 groupby 进行计算(groupby.mean() 不解决唯一的“批次”)
问题描述
我有一个看起来像这样的大 df(小部分):
Product Batch Inv_type Item Total_cost
Big Boy 1,000 Packaging Cans 664
Big Boy 1,000 Raw Material Flour 800
Big Boy 1,000 Packaging Label 300
Big Boy 1,000 Raw Material Sugar 900
Big Boy 1,001 Packaging Cans 782
Big Boy 1,001 Raw Material Flour 560
Big Boy 1,001 Packaging Label 300
Big Boy 1,001 Raw Material Sugar 522
Hit Ton 1,002 Raw Material Flour 560
Hit Ton 1,002 Packaging Label 300
Hit Ton 1,002 Raw Material Sugar 522
它基本上是一个材料清单。每个产品由多个价值不同的物品组成,要么是包装,要么是原材料。
I need this:
Sum of all Packing Costs / count of unique Batch #'s
Sum of all Raw Material Costs/ count of unique Batch #'s
所以它看起来像这样(括号仅显示公式):
Product Inv_Type Avg_cost_per_batch
Big Boy Packaging 1,023 (2,046 / 2)
Raw Material 1,391 (2,782 / 2)
HIT TON Packaging 300 (300 / 1)
Raw Material 1,082 (1,082 / 1)
这将为我提供每批产品的平均总包装成本和总原材料。
我想将 添加Avg_cost_per_batch
到新列df['Avg_batch_cost']
中,这样我就可以按此细分绘制每种产品的平均成本。
如果最适合'Tidy Data'
格式,则可以在产品名称所在的每一行添加它。
这是我尝试过的:
首先删除重复项
dropdups = df.drop_duplicates(subset='Batch', inplace=True, ignore_index=True)
然后枢轴
pvdups = pd.pivot_table(dropdups, values='Batch', index='Product', aggfunc='count')
这似乎让我了解了按产品分类的唯一批次计数
然后我将原始df分组:
prod_totals = df.groupby(['Product', 'Inv_type']).sum()['Total_cost']
那么,我如何获取数据透视表 df 和 groupby 系列,并使用显示的总成本/唯一批号的计数来创建按产品细分的平均成本?
解决方案
- 用于
pandas.core.groupby.DataFrameGroupBy.agg
聚合'Total_cost'
withsum
和'Batch'
withnunique
。 - 然后将两列分开以获得所需的输出。
# aggregate sum of Total_cost and the unique count of Batch
g = df.groupby(['Product', 'Inv_type']).agg({'Total_cost': sum, 'Batch': 'nunique'})
# calculate Avg_cost_per_batch
g['Avg_cost_per_batch'] = g.Total_cost.div(g.Batch)
# display(g)
Total_cost Batch Avg_cost_per_batch
Product Inv_type
Big Boy Packaging 2046 2 1023.0
Raw Material 2782 2 1391.0
Hit Ton Packaging 300 1 300.0
Raw Material 1082 1 1082.0
推荐阅读
- php - 迁移到 PHP 7.3 服务器甚至禁用所有插件后出现技术困难的 Wordpress 博客
- python - python如何在多线程中管理变量
- c - 如何使用指向指针的指针在 main 中返回?
- sql - 如何在 Bash 脚本中删除字符串周围的单引号?
- ios - 在 iOS 上测试 nativescript 应用程序在启动屏幕后显示空白屏幕
- php - 如何将 SimpleXMLObject 转换为 PHP 数组和字符串?
- kotlin - 在不可为空的字段中测试驱动器的最佳方法
- python - 用于损坏链接的 Selenium Webdriver 代码片段
- rest - 如何在 Google Cloud Platform 上记录随 api 请求发送的数据
- typescript - 类型“N[P]”不能用于索引类型“IComponents”
'