Search code examples
pythonpandasdataframepython-itertools

compute all permutations of a list in a dataframe column


I am trying to compute all permutations of a list or column in a df while keeping an id column.

input df
    id    list
    1     foo bar
    2     dog cat

desired df output
    id    list
    1     foo bar
    1     bar foo
    2     dog cat
    2     cat dog

Solution

  • IIUC just using permutations from itertools, then it is unnest

    df['list']=df['list'].str.split(' ')
    import itertools
    df['list']=[list(itertools.permutations(x)) for x in df['list']]
    pd.DataFrame({'id':df.id.repeat(df['list'].str.len()),'list':np.concatenate(df['list'].values).tolist()})
    Out[522]: 
       id        list
    0   1  [foo, bar]
    0   1  [bar, foo]
    1   2  [dog, cat]
    1   2  [cat, dog]