0

I have this dataframe:

12  2   17
16  4   16
2   19  11

I want to get, accross its columns, the following output

[ [12,16,2],[2,4,19],[17,16,11],[[12,16,2],[2,4,19]],[[2,4,19],[17,16,11]],[[12,16,2],[2,4,19],[17,16,11]]  ]

I have this code which yield the first 3 possibilities only:

    from itertools import combinations
    resultTmp2 = []
    for j in range(1, len(dataframe.columns) + 1):
      resultTmp = []
      for xVal in list(combinations(dataframe.iloc[:len(dataframe) + 1,j-1],  len(dataframe)  )): 
        resultTmp.append(list(xVal)) 
      resultTmp2.append(resultTmp)
    print(resultTmp2)

How to update my code so that it yields correct mentioned output?

Sam
  • 308
  • 2
  • 7

2 Answers2

0

You've tagged your problem with pandas, but it might be easier to work with pure python to generate your expected output. I suspect it is closely related to this question: Get all possible (2^N) combinations of a list’s elements, of any length

Accounting for the fact that combinations returns tuples, and your expected output has lists; and that your size 1 combinations are not enclosed in a separate list:

import itertools
import pandas as pd

df = pd.read_clipboard(header=None) # Your df here

my_list = df.to_numpy().T.tolist()
# [[12, 16, 2], [2, 4, 19], [17, 16, 11]]

out = my_list + list(
    itertools.chain.from_iterable(
        map(list, itertools.combinations(my_list, r))
        for r in range(2, len(my_list) + 1)
    )
)

out:

[[12, 16, 2], [2, 4, 19], [17, 16, 11], [[12, 16, 2], [2, 4, 19]], [[12, 16, 2], [17, 16, 11]], [[2, 4, 19], [17, 16, 11]], [[12, 16, 2], [2, 4, 19], [17, 16, 11]]]
Chrysophylaxs
  • 5,818
  • 3
  • 10
  • 21
0

You seem to be looking for the powerset of your list.

This is a straightforward way to produce it:

from itertools import combinations

src = [[12, 16, 2], [2, 4, 19], [17, 16, 11]]
for r in range(len(src)):
    print(*list(combinations(src, r+1)), sep="\n")

Output:

([12, 16, 2],)
([2, 4, 19],)
([17, 16, 11],)
([12, 16, 2], [2, 4, 19])
([12, 16, 2], [17, 16, 11])
([2, 4, 19], [17, 16, 11])
([12, 16, 2], [2, 4, 19], [17, 16, 11])

You can do the proper data manipulation to get the results out of the tuples if you want.


EDIT

Based on you comment, it seems you don't want the full powerset, but just the combinations that include only contiguous elements in the original list.

You can try this out then:

src = [[12, 16, 2], [2, 4, 19], [17, 16, 11]]
for r in range(len(src)):
    for s in range(len(src) - r):
        print(src[r:r+s+1])

Output:

[[12, 16, 2]]
[[12, 16, 2], [2, 4, 19]]
[[12, 16, 2], [2, 4, 19], [17, 16, 11]]
[[2, 4, 19]]
[[2, 4, 19], [17, 16, 11]]
[[17, 16, 11]]
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36