【问题标题】:Pandas get row combination and group熊猫获得行组合和分组
【发布时间】:2021-05-19 07:15:33
【问题描述】:

我有一个 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]])

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我们可以先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   1
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 2018-11-07
      • 2022-09-27
      • 2017-02-16
      相关资源
      最近更新 更多