Search code examples
pythonpandaspermutation

Permutation of a number of rows of a dataframe using pandas


I have a data frame of this kind:

d = pd.DataFrame({'Job': ['A', 'B', 'C', 'D', 'E'],
        'Machine1': [1,3,2,4,3], 'Machine2': [2,0,5,1,2]})

For the index 'Job', I need to find all permutations of length 5, basically (5 factorial) permutations. The length of the index may change for a different scenario, so I am not looking for a code specific to 5 jobs only.

Expected output: A,B,C,D,E; A,C,D,E,B; E,D,C,B,A ... and so on up to 120 such ways. In basic math, it is a permutation expressed as 5P5


Solution

  • I think you're looking for the built-in function itertools.permutations():

    import itertools as it
    permutations = list(it.permutations(d['Job']))
    

    Output:

    >>> permutations
    [('A', 'B', 'C', 'D', 'E'),
     ('A', 'B', 'C', 'E', 'D'),
     ('A', 'B', 'D', 'C', 'E'),
     ('A', 'B', 'D', 'E', 'C'),
     ('A', 'B', 'E', 'C', 'D'),
    ...
    
    >>> len(permutations)
    120