I have the following table with 4 columns:
JavaScript
x
5
1
cl1: a, b, c
2
cl2: x, y, z
3
cl3: 1, 2, 3
4
cl4: m, n
5
My desired Output in a df:
JavaScript
1
14
14
1
a_x_1_m
2
a_x_1_n
3
a_x_2_m
4
a_x_2_n
5
a_x_3_m
6
a_x_3_n
7
a_y_1_m
8
a_y_1_n
9
a_y_2_m
10
a_y_2_n
11
12
c_z_3_m
13
c_z_3_n
14
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:
JavaScript
1
3
1
cols_to_extract = ['cl1', 'cl2', 'cl3', 'cl4']
2
cols_to_list = [df[col].tolist() for col in cols_to_extract]
3
Now if you have any list that contains elements other than strings, you need to convert them:
JavaScript
1
2
1
cols_to_list = [[str(m) for m in n] for n in cols_to_list]
2
and finally use itertools
to derive the product of these lists:
JavaScript
1
5
1
import itertools
2
3
for comb in map('_'.join, itertools.product(*cols_to_list)):
4
print(comb)
5
And the result should be similar to the one below:
JavaScript
1
5
1
a_x_1_m
2
a_x_1_n
3
a_x_2_m
4
5