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

>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)

Leave a Reply