Search code examples
pythonlistpandascombinationspython-itertools

Python, itertools.combinations results to different rows in pandas


Lets say I have a list:

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

I want to get pairwise combinations which are:

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

Then I want to save the output to rows in pandas. Resulting output should look like this:

     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]]

I have to do it for a list which consists of 1000 elements. Any help will be highly appreciated


Solution

  • You can group the pairs by their first element:

    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)))
    

    Demo:

    >>> 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