Encoded Table from all combinations of a list

Question:

I’ve spent a little while on this and got an answer but seems a little convoluted so curious if people have a better solution.

Given a list I want a table indicating all the possible combinations between the elements.

sample_list = ['a', 'b', 'c', 'd']

(pd.concat(
    [
     pd.DataFrame(
         [dict.fromkeys(i, 1) for i in combinations(sample_list, j)]
         ) for j in range(len(sample_list)+1)
     ]).
    fillna(0).
    reset_index(drop = True)
    )

With the result, as desired:

      a    b    c    d
0   0.0  0.0  0.0  0.0
1   1.0  0.0  0.0  0.0
2   0.0  1.0  0.0  0.0
3   0.0  0.0  1.0  0.0
4   0.0  0.0  0.0  1.0
5   1.0  1.0  0.0  0.0
6   1.0  0.0  1.0  0.0
7   1.0  0.0  0.0  1.0
8   0.0  1.0  1.0  0.0
9   0.0  1.0  0.0  1.0
10  0.0  0.0  1.0  1.0
11  1.0  1.0  1.0  0.0
12  1.0  1.0  0.0  1.0
13  1.0  0.0  1.0  1.0
14  0.0  1.0  1.0  1.0
15  1.0  1.0  1.0  1.0

For learning purposes would like to know better solutions.

Thanks

Asked By: Quixotic22

||

Answers:

Check Below code

import itertools
import pandas as pd

sample_list = ['a', 'b', 'c', 'd']

pd.DataFrame(list(itertools.product([0, 1], repeat=len(sample_list))), columns=sample_list)

Output:

enter image description here

Answered By: Abhishek
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.