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

Combinations of all possible values from single columns

I’ve tried to find this specific question answered but not had any luck. Suppose I have a pandas dataframe with the following columns:

A B C
1 2 3
4 5 6

All I’m trying to achieve is a new dataframe that has all combinations of the unique values in the individual columns themselves, so:

A B C
1 2 3
4 2 3
1 2 6
4 2 6
1 5 3
1 5 6
4 5 6
4 5 3

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 :

You can try to get the all possible combination first using any preferable methods. I will go with "Itertools.product".

from itertools import product
# Get unq values
unique_values = [df[col].unique() for col in df.columns]
# Get possible combinations of unq values
combinations = list(product(*unique_values))
combined_df = pd.DataFrame(combinations, columns=df.columns)
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