Home > database >  Create a dataframe from an itertools.combinations object
Create a dataframe from an itertools.combinations object

Time:06-06

I am wondering whether there is a more efficient way to create a dataframe from a combinations object in Python. For example:

I have a list: lst = [1, 2, 3, 4, 5] and pick_size = 3

combos_obj = itertools.combinations(lst, pick_size)

So far I have been using list comprehension:

combos = [list(i) for i in combos_obj]
df = pd.DataFrame(combos)

which gives me the result I want, but is there a more efficient way to do this?

CodePudding user response:

Just create a dataframe directly from the generator that itertools.combinations returns:

>>> combos_obj = itertools.combinations(lst, pick_size)
>>> combos_obj
<itertools.combinations at 0x12ba9d220>

>>> df = pd.DataFrame(combos_obj)
>>> df
   0  1  2
0  1  2  3
1  1  2  4
2  1  2  5
3  1  3  4
4  1  3  5
5  1  4  5
6  2  3  4
7  2  3  5
8  2  4  5
9  3  4  5
  • Related