【问题标题】:Finding all 2 Part Permutations in a Single Column Associated with an ID在与 ID 关联的单个列中查找所有 2 个部分排列
【发布时间】:2021-03-05 00:23:05
【问题描述】:

我正在尝试做以下事情:

group id    value
   1         a
   1         b
   1         c
   2         b
   2         c
   2         d

进入这种性质的东西:

group id    value1   value2
   1         a        b
   1         a        c
   1         b        a
   1         b        c  
   1         c        a
   1         c        b
   2         b        c
   2         b        d
   2         c        b
   2         c        d
   2         d        b
   2         d        c

我在 R 中找到了解决方案,但在 Python 中找不到类似的解决方案。

【问题讨论】:

    标签: python permutation


    【解决方案1】:

    您可以按group_id分组并申请itertools.permutations

    import pandas as pd
    df = pd.DataFrame({ 'group_id': [1]*3 + [2]*3, 'value': list('abcbcd') })
    
    from itertools import permutations
    (df.groupby('group_id')
       .apply(lambda x: pd.DataFrame(permutations(x.value, 2), columns=['value1', 'value2']))
       .droplevel(1))
    

    输出:

        value1   value2
    group_id     
    1        a        b
    1        a        c
    1        b        a
    1        b        c
    1        c        a
    1        c        b
    2        b        c
    2        b        d
    2        c        b
    2        c        d
    2        d        b
    2        d        c
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-02
      相关资源
      最近更新 更多