我在熊猫df有一张桌子
product_id_x product_id_y
1 2
1 3
1 4
3 7
3 11
3 14
3 2
and so on around (1000 rows)
我想找到带有product_id_y的每个product_id_x的组合数。
即。 1个具有1-2,1-3,1-4的组合(总共3个组合)
同样,3个共有4个组合。
并创建一个数据框df2
product_id_x combinations
1 3
3 4
and so on ..(distinct product_id_x's)
我应该采取什么方法?
我在python上的技能是初学者。
提前致谢。
最佳答案
您可以在groupby
列上使用agg
with product_id_x
:
df2 = df.groupby(['product_id_x']).agg(['count'])
或者,您可以直接在组上使用
size
函数来获取每个组的大小:df2 = df.groupby(['product_id_x']).size()