【问题标题】:Is there an optimal way to get all combinations of values in a grouped pandas dataframe?是否有一种最佳方式来获取分组熊猫数据框中的所有值组合?
【发布时间】:2021-04-26 06:42:13
【问题描述】:

示例数据框如下

df = pd.DataFrame({'ID': ['a', 'a', 'a', 'b', 'b', 'c', 'c'], 
                   'color': ['red', 'blue', 'green', 'red', 'blue', 'red', 'green']})

在按 ID 分组后,我想要 2 列包含颜色字段的所有组合。
我想要如下所示的结果数据框

ID color1 color2
a red blue
a red green
a blue red
a blue green
a green red
a green blue
b red blue
b blue red
c red green
c green red

我曾尝试使用 itertools.permutations,但我正在寻找更直接的方法或更多利用 Pandas 的解决方案。

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    我认为您可以进行自我合并和查询:

    df.merge(df, on='ID', suffixes=[1,2]).query('color1 != color2')
    

    或类似,合并然后过滤:

    (df.merge(df, on='ID', suffixes=[1,2])
       .loc[lambda x: x['color1'] != x['color2']]
    )
    

    输出:

       ID color1 color2
    1   a    red   blue
    2   a    red  green
    3   a   blue    red
    5   a   blue  green
    6   a  green    red
    7   a  green   blue
    10  b    red   blue
    11  b   blue    red
    14  c    red  green
    15  c  green    red
    

    【讨论】:

      【解决方案2】:

      你可以使用这个方法:

      from itertools import permutations
      
      s = df.groupby('ID')['color']\
            .apply(lambda x: list(permutations(x, 2))).explode()
      dfi= pd.DataFrame().from_records(s, index=s.index, columns=['color1', 'color2'])
      dfi
      

      输出:

         color1 color2
      ID              
      a     red   blue
      a     red  green
      a    blue    red
      a    blue  green
      a   green    red
      a   green   blue
      b     red   blue
      b    blue    red
      c     red  green
      c   green    red
      

      时间安排:

      #这个方法

      每个循环 3.18 ms ± 23.9 µs(7 次运行的平均值 ± 标准偏差,每次 100 个循环)

      #自加入方式

      每个循环 5.96 ms ± 105 µs(平均值 ± 标准偏差,7 次运行,每次 100 个循环)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-29
        • 1970-01-01
        • 2016-07-14
        • 2019-03-08
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多