在pandas df中查找列组合的计数 [英] Find count of combinations of column in pandas df

查看:49
本文介绍了在pandas df中查找列组合的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Pandas df 中有一张桌子

i have a table in pandas 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_x 和 product_id_y 的组合数.

i want to find the count of combinations for each product_id_x with product_id_y.

即.1 与 1-2,1-3,1-4 组合(共 3 个组合)同样3有4种组合.

ie. 1 has combinations with 1-2,1-3,1-4(total 3 combinations) similarly 3 has total 4 combinations.

并创建一个具有

product_id_x   combinations
1               3
3               4

and so on ..(distinct product_id_x's)

我应该遵循什么方法?我的 Python 技能处于初级水平.提前致谢.

what approach should i follow? my skills on python are at a beginner level. Thanks in advance.

推荐答案

size 计算每个列值对一起出现的行数.count 计数相同的东西,但它们不为空.由于您没有提到任何有关空值的内容,我将在 groupby 之后使用 size,然后使用 unstack

size counts the number of rows each of the column value pairs happen together. count counts the same thing but where they are not null. Since you did not mention anything about nulls, I'll use size after a groupby, then unstack

df.groupby(['product_id_x', 'product_id_y']).size().unstack(fill_value=0)

这篇关于在pandas df中查找列组合的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆