Search code examples
pythonpandascombinations

generate all possible combinations with multiple colums in pan das


I have 3 columns col_1, col_2, col_3. The unique values of the columns are

col_1 => [1,2]

col_2 => [“yes”, “no”]

col_3 => [4, 5, 6]

I want to generate a pandas df that has all possible combinations as rows:

col_1 col_2 col_3
1 yes 4
1 yes 5
1 yes 6
1 no 4
1 no 5
1 no 6
2 yes 4
2 yes 5
2 yes 6
2 no 4
2 no 5
2 no 6

so, the number of rows are 2 x 2 x 4 = 12

Is there any way to generate such table using pandas?


Solution

  • You can use pandas.MultiIndex.from_product:

    col_1 = [1,2]
    col_2 = ["yes", "no"]
    col_3 = [4, 5, 6]
    
    df = (pd.MultiIndex.from_product([col_1, col_2, col_3],
                                    names=['col_1', 'col_2', 'col_3'])
            .to_frame().reset_index(drop=True)
         )
    

    output:

        col_1 col_2  col_3
    0       1   yes      4
    1       1   yes      5
    2       1   yes      6
    3       1    no      4
    4       1    no      5
    5       1    no      6
    6       2   yes      4
    7       2   yes      5
    8       2   yes      6
    9       2    no      4
    10      2    no      5
    11      2    no      6