Python,itertools.combinations导致pandas中的不同行

时间:2017-03-25 12:00:30

标签: python list pandas combinations itertools

假设我有一个清单:

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个元素的列表执行此操作。任何帮助将受到高度赞赏

1 个答案:

答案 0 :(得分: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