合并行和计数值

2024-05-16 23:07:41 发布

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

我有一个类似这样的数据帧:

OrderNum Product Quantity

1 Gum 2

1 Candy 4

2 Chocolate 8

3 Gum 3

3 Soda 1

4 Chocolate 2

5 Gum 2

5 Soda 2

对于订购的每种产品,我想根据订单号的相同情况,找出其他哪些产品以及每种产品的订购数量

我想看看这样的东西:

Gum 7 Candy 4 Soda 3

Candy 4 Gum 2

Chocolate 10

etc.

谢谢你的帮助

康纳


Tags: 数据数量产品etc情况productquantity订单号
1条回答
网友
1楼 · 发布于 2024-05-16 23:07:41

听起来你想做的是找出每个元素之间的关联。如果两个(或更多)订单有“糖果”,那么它们包含多少其他产品

这是我能想到的最好的了。首先,按每个产品分组,以便找到拥有该产品的所有订单。然后,从原始数据帧中提取子集,得到每个乘积的数量之和

# group by the products
products = df.groupby("Product")

# each groupby element is a tuple
# the first entry is the value (in this case, the Product)
# the second is a dataframe
# iterate through each of these groups
for p in products:
  sub_select = df[df["OrderNum"].isin(p[1]['OrderNum'])]
  quantities = sub_select.groupby("Product").Quantity.sum()

  # print the name of the product that we grouped by
  # and convert the sums to a dictionary for easier reading
  print(p[0], quantities.to_dict())
  # Candy :  {'Candy': 4, 'Gum': 2}
  # Chocolate :  {'Chocolate': 10}
  # Gum :  {'Candy': 4, 'Soda': 3, 'Gum': 7}
  # Soda :  {'Soda': 3, 'Gum': 5}

sub_select将是原始数据帧的子集。例如,它将包含包含糖果的所有订单的所有行quantities然后将所有这些订单按产品分组,以获得所有匹配订单中每个产品的数量总和

相关问题 更多 >