Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Permutation of a number of rows of a dataframe using pandas

I have a data frame of this kind

d = {'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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading