首页 > 解决方案 > 熊猫获得行组合和分组

问题描述

我有一个df

在此处输入图像描述

我必须找到 Group 的所有组合(比如说 2 对),然后必须将它们分组到唯一的 ID 中

输出:

在此处输入图像描述

目前我找到了一种生成所有组合的方法,但似乎无法按唯一 ID 分组

我也提到了下面的链接: Pandas 在预算内找到所有行组合

生成对的代码:

from itertools import combinations
li_4 =[]
for index in list(combinations(df.group.unique(),2)):
       li_4.append([index[0],index[1]])

标签: pythonpandas

解决方案


我们可以这样做merge并将np.sort结果传递给crosstab删除重复项后drop_duplicates

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   1

推荐阅读