Search code examples
pythonpandassequences

Pandas data-frame creation as permutations of 2 series?


I have data set with two columns

ColA ColB
1    1 
2    2
3    3

I want to create resultant frame of

ColA ColB
1    1
1    2
1    3
2    1
2    2
2    3
3    1
3    2
3    3

Solution

  • You could use itertools for this

    import pandas as pd
    import itertools
    

    Create the original dataframe

    df = pd.DataFrame([[1,2,3]]*2, index=['ColA', 'ColB']).T
    

    Permute the two columns of the dataframe you are interested in:

    df2 = pd.DataFrame([e for e in itertools.product(df.ColA, df.ColB)], columns=df.columns)
    
    df2
        ColA  ColB
    0   1     1
    1   1     2
    2   1     3
    3   2     1
    4   2     2
    5   2     3
    6   3     1
    7   3     2
    8   3     3