【问题标题】:How to use itertools combinations in a dataframe如何在数据框中使用 itertools 组合
【发布时间】:2019-02-08 20:17:06
【问题描述】:

我有一个这样的 4 列数据框

Asset1 Asset2 Asset3 Asset4 

 a      b      c      d  
 e      f      g      h  

我想使用itertools.combinations 创建一个列来给我一个独特组合的结果,所以理想的输出是:

  Asset1 Asset2 Asset3 Asset4   test

  a      b      c      d        [abc, abd, bcd, acd]

  e      f      g      h        [efg, efh, egh, fgh]

我尝试使用.join() 和组合但不起作用。有什么想法吗?

【问题讨论】:

    标签: python python-3.x pandas dataframe combinations


    【解决方案1】:

    欢迎来到 SO!

    我建议使用lambda row-wise (axis=1):

    from itertools import combinations
    import pandas as pd
    
    df = pd.DataFrame({'Asset1':('a','e'), 'Asset2': ('b','f'), 'Asset3': ('c', 'g'),  'Asset4': ('d', 'h')})
    df['combinations'] = df.apply(lambda r: list(combinations(r, 3)), axis=1)
    
    print(df)
    

    输出:

      Asset1                      ...                                                       combinations
    0      a                      ...                       [(a, b, c), (a, b, d), (a, c, d), (b, c, d)]
    1      e                      ...                       [(e, f, g), (e, f, h), (e, g, h), (f, g, h)]
    
    [2 rows x 5 columns]
    

    如果您稍后只对组合进行迭代,您也可以跳过 list(combinations... - 这样您将节省一些内存并将计算延迟到访问 df['combinations'] 的那一刻:

    df['combinations'] = df.apply(lambda r: combinations(r, 3), axis=1)
    print(df)
    

    然后你会在combinations 列中得到一个非常神秘的对象:

      Asset1                        ...                                                               combinations
    0      a                        ...                          <itertools.combinations object at 0x0000022392...
    1      e                        ...                          <itertools.combinations object at 0x0000022392...
    
    [2 rows x 5 columns]
    

    【讨论】:

    • 非常感谢。当我运行这段代码时,它显示一条错误消息:'list' object is not callable", 'occured at index 0'。你对此有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多