Skip to content
Advertisement

Using itertools for combinations in python

I have the following table with 4 columns:

cl1: a, b, c   
cl2: x, y, z  
cl3: 1, 2, 3  
cl4: m, n  

My desired Output in a df:

a_x_1_m  
a_x_1_n  
a_x_2_m  
a_x_2_n  
a_x_3_m  
a_x_3_n  
a_y_1_m  
a_y_1_n  
a_y_2_m  
a_y_2_n  
 ...  
c_z_3_m  
c_z_3_n

I need it to loop through and combine all possible combinations. What is the best way to do this using python?

Advertisement

Answer

I assume that by table you mean a pandas dataframe, so the first step would be to collect the columns of interest into a list of lists:

cols_to_extract = ['cl1', 'cl2', 'cl3', 'cl4']
cols_to_list = [df[col].tolist() for col in cols_to_extract]

Now if you have any list that contains elements other than strings, you need to convert them:

cols_to_list = [[str(m) for m in n] for n in cols_to_list]

and finally use itertools to derive the product of these lists:

import itertools

for comb in map('_'.join, itertools.product(*cols_to_list)):
    print(comb)

And the result should be similar to the one below:

a_x_1_m
a_x_1_n
a_x_2_m
...
Advertisement