【问题标题】:Python, itertools.combinations results to different rows in pandasPython,itertools.combinations 结果到熊猫中的不同行
【发布时间】:2017-08-18 08:51:59
【问题描述】:

假设我有一个列表:

list = [1, 2, 3, 4, 5]

我想得到成对的组合,它们是:

[1,2] [1,3] [1,4] [1,5] [2,3] [2,4] [2,5] [3,4] [3,5] [4,5]

然后我想将输出保存到 pandas 中的行。结果输出应如下所示:

     Combinations
0  [[1,2],[1,3],[1,4],[1,5]]
1  [[2,3],[2,4],[2,5]]
2  [[3,4], [3,5]]
3  [[4,5]]

我必须为包含 1000 个元素的列表执行此操作。任何帮助将不胜感激

【问题讨论】:

    标签: python list pandas combinations itertools


    【解决方案1】:

    您可以按它们的第一个元素对它们进行分组:

    from itertools import combinations, groupby
    from pandas import Series
    from operator import itemgetter
    
    combined = combinations(inputlist, 2)
    series = Series(list(g) 
                    for k, g in groupby(combined, key=itemgetter(0)))
    

    演示:

    >>> from itertools import combinations, groupby
    >>> from pandas import Series
    >>> from operator import itemgetter
    >>> inputlist = [1, 2, 3, 4, 5]
    >>> combined = combinations(inputlist, 2)
    >>> Series(list(g) for k, g in groupby(combined, key=itemgetter(0)))
    0    [(1, 2), (1, 3), (1, 4), (1, 5)]
    1            [(2, 3), (2, 4), (2, 5)]
    2                    [(3, 4), (3, 5)]
    3                            [(4, 5)]
    dtype: object
    

    【讨论】:

    • 如果我有一个类似的函数:results = [] for x,y in itertools.combinations(df['hash_1'], 2): if str(x) != str(y ): xyz = (64 - (x - y))/64 print(x,y,xyz) results.append(xyz)
    • @edyvedy13:用combined = ((x, y, (64 - (x - y))/64) for x, y in combinations(df['hash_1'], 2) if x ! = y)替换我的combined
    猜你喜欢
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 2020-08-27
    • 2017-06-22
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    相关资源
    最近更新 更多