我有一个df

我必须找到Group的所有组合(假设是2对),然后必须跨唯一ID对它们进行分组
输出:

目前,我找到了一种生成所有组合的方法,但似乎不能按唯一ID进行分组
我也参考了下面的链接:Pandas find all combinations of rows under a budget
生成配对的代码:
from itertools import combinations
li_4 =[]
for index in list(combinations(df.group.unique(),2)):
li_4.append([index[0],index[1]])发布于 2021-05-19 07:15:33
我们可以先执行merge,然后执行np.sort,并在使用drop_duplicates删除重复项后将结果传递给crosstab
s = df.merge(df,on='Id')
s['New'] = list(map(lambda x : ''.join(x),np.sort(s[['Group_x','Group_y']].values,axis=1).tolist()))
s = s.drop_duplicates(['Id','New'])
s = pd.crosstab(s.Id,s.New)
s
Out[88]:
New aa ab ac ad af bb bc bd be bf cc cd dd de ee ff
Id
2 1 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0
3 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 0
4 1 1 0 0 1 1 0 0 0 1 0 0 0 0 0 1https://stackoverflow.com/questions/67595026
复制相似问题