如何在 Pandas 的 groupby 中获取不同值的计数?

3
我希望能够按订单编号获取产品的数量。我已经得到了总产品数量(感谢另一个SO用户的帮助),但是我无法计算出不同产品的数量。
以下是我的代码:
data['total_productcount'] = data.groupby(['order_number'])['order_number'].transform('size')

并且它会给予:

order_number          product_id      total_productcount   
171-1046037-0511522   4260179734731   5                    
171-1046037-0511522   4054673034394   5                   
171-1046037-0511522   4054673001235   5                   
171-1046037-0511522   4054673005752   5                    
171-1046037-0511522   5011385960075   5                    
171-1046037-0511522   5011385960075   5    

这是我想要生成的数据框(包括:distinct_productcount)

order_number          product_id      total_productcount   distict_productcount
171-1046037-0511522   4260179734731   5                    1
171-1046037-0511522   4054673034394   5                    1
171-1046037-0511522   4054673001235   5                    1
171-1046037-0511522   4054673005752   5                    1
171-1046037-0511522   5011385960075   5                    1
171-1046037-0511522   5011385960075   5                    2

如何生成“distinct_productcount”?
1个回答

4
data.groupby('order_number').product_id.nunique()

您可以使用 transformjoin 获取新的列。

通过transform

s = data.groupby('order_number').product_id.transform('nunique')
df = df.assign(distinct_productcount=s)

通过join函数
s = data.groupby('order_number').product_id.nunique()
df = df.join(s.rename('distinct_productcount'), on='order_number')

我尝试了您的建议,如下所示:data['distinct_product_count'] = data.groupby('order_number').product_id.nunique() 但是该列为空? - Jabb
刚刚检查了你的解决方案。它们给出了“total_productcount”而不是不同的产品数量。我正在一个包含许多订单号的较大数据框上尝试这个。 - Jabb
你正在重新分配给数据框吗?df = df.assign(distinct_productcount=s) - piRSquared
@Jabb 如果我还能有任何用处,我需要看到样本数据。 - piRSquared
@Jabb,你只需要足够的数据来证明你的观点。你可以在帖子中贴上50行数据而没有问题。SO绝对是正确的地方。然而,如果你愿意的话,人们经常使用pastebin。 - piRSquared
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接