一列中唯一对的数量 - 熊猫

Bon*_*ndo 3 python pandas pandas-groupby

我在为pandas中的数据帧生成统计信息时遇到了一些问题.我的数据框看起来像这样(我省略了索引):

id    type  
1      A
2      B
3      A
1      B
3      B
2      C
4      B
4      C
Run Code Online (Sandbox Code Playgroud)

重要的是,每个idtype分配了两个值,从上面的例子中可以看出.我想计算所有type组合出现次数(所以计算id给定type组合的唯一数量),所以我想得到这样一个数据帧:

type    count
A, B      2
A, C      0
B, C      2
Run Code Online (Sandbox Code Playgroud)

我试过groupby很多方面,但是徒劳无功.我可以使用for-loop和多行代码来做这种"计数" ,但我相信必须有优雅和适当的(用python术语)解决这个问题.

提前感谢任何提示.

piR*_*red 5

pd.value_countsitertools.combinations

from itertools import combinations

pd.value_counts(
    [(x, y) for _, d in df.groupby('id') for x, y in combinations(d.type, 2)]
)

(A, B)    2
(B, C)    2
dtype: int64
Run Code Online (Sandbox Code Playgroud)