我对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]
})
我自己的解决方案:
如果客户的名字在“s”之后以字母开头,则不起作用,因为它可能排序在“小计”下面
# Intermediate Subtotal Dataframe
Product Customer Qty
0 Item A Subtotal 15
1 Item B Subtotal 21
2 Item C Subtotal 1
我在工作流程中经常遇到这个问题。你可以做的一件事有点老套,但实际上是用“[Subtotal]”代替“Subtotal”。它周围的括号将为您正确排序
这是我问的问题&;以前也有人回答过类似的问题
link 1
link 2
相关问题 更多 >
编程相关推荐