Python 合并行和计数值
我有一个与此类似的数据帧:Python 合并行和计数值,python,merge,count,row,Python,Merge,Count,Row,我有一个与此类似的数据帧: 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. 谢谢你的帮助 Conn
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.
谢谢你的帮助
Connor听起来你想做的就是找到每个元素之间的关联。如果两个(或更多)订单上有“糖果”,那么它们包含多少其他产品 这是我能想到的最好的了。首先,按每个产品分组,以查找所有拥有该产品的订单。然后,从原始数据帧中获取该子集,并得到每个乘积的数量之和
# 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
将是原始数据帧的子集。例如,它将包含包含糖果的所有订单的所有行<编码>数量然后按产品将所有订单分组,以获得所有匹配订单中每个产品的数量总和。我对您的预期输出感到困惑。你是怎么得到糖果4,口香糖2的?第一行和最后一行对我来说很有意义(它是按产品分组的数量的总和)。但第二个不符合这种模式。OrderNum 1上的糖果订购了4次,OrderNum 1上的口香糖订购了2次。因为糖果没有在其他地方订购,所以用糖果订购的产品的产量是糖果4和口香糖2。我想我现在知道了。有3个订单有口香糖。在这些订单中,一共订购了7套口香糖(3个不同的订单),4件糖果和3件苏打水。太棒了!你能告诉我如何在python中实现这一点吗?非常感谢!这是完美的,非常有帮助。没问题。如果你不介意接受这个答案,那将非常感谢!