Python是否在输出中使用“小计”值创建Groupby?

2024-10-05 14:28:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python非常陌生,在源数据框['Product','Customer']上使用pandas groupby函数时,我很难简化创建“小计值”的步骤

请帮助提供任何提示和解决方案。谢谢大家!

# Desired Output
Product Customer    Qty
Item A  Cust1       5
        Cust4       10
        Subtotal    15
Item B  Cust1       15
        Cust2       5
        Cust6       1
        Subtotal    21
Item C  Cust3       1
        Subtotal    1

# Source Dataframe
    Product Customer  Qty
0   Item A  Cust1     5
1   Item A  Cust4     10
2   Item B  Cust1     15
3   Item B  Cust2     5
4   Item B  Cust6     1
5   Item C  Cust3     1

# Source Dataframe code
source_df = pd.DataFrame({
    'Product'  : ['Item A', 'Item A', 'Item B', 'Item B','Item B', 'Item C'],
    'Customer' : ['Cust1', 'Cust4', 'Cust1', 'Cust2', 'Cust6', 'Cust3'],
    'Qty'      : [5,10,15,5,1,1]
})

我自己的解决方案:

  1. 按“产品”创建一个中间数据框groupby,并使用一列填充“小计”字符串值聚合“数量”
  2. 连接源数据帧和中间数据帧
  3. 再次对[‘产品’、‘客户’]执行groupby以获得所需的输出

如果客户的名字在“s”之后以字母开头,则不起作用,因为它可能排序在“小计”下面

# Intermediate Subtotal Dataframe
    Product Customer    Qty
0   Item A  Subtotal    15
1   Item B  Subtotal    21
2   Item C  Subtotal    1

Tags: 数据sourcedataframecustomerproduct解决方案itemqty
1条回答
网友
1楼 · 发布于 2024-10-05 14:28:08

我在工作流程中经常遇到这个问题。你可以做的一件事有点老套,但实际上是用“[Subtotal]”代替“Subtotal”。它周围的括号将为您正确排序

这是我问的问题&;以前也有人回答过类似的问题

link 1

link 2

相关问题 更多 >