首页 > 解决方案 > 使用 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 系列,并使用显示的总成本/唯一批号的计数来创建按产品细分的平均成本?

标签: pythonpandas

解决方案


# 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

推荐阅读