在 python 中使用 itertools 进行组合

Using itertools for combinations in python

我有以下 table 4 列:

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

我想要的 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

我需要它遍历并组合所有可能的组合。使用 python 执行此操作的最佳方法是什么?

table,我假设你只是指嵌套列表(也适用于嵌套元组或类似的)。

import itertools

inputs = [["a", "b", "c"], ["x", "y", "z"], [1, 2, 3], ["m", "n"]]
output = list(itertools.product(*inputs))

我假设 table 是指 pandas 数据框,因此第一步是将感兴趣的列收集到列表列表中:

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

现在,如果您有任何包含字符串以外元素的列表,则需要转换它们:

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

最后使用itertools推导这些列表的乘积:

import itertools

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

结果应该类似于下面的结果:

a_x_1_m
a_x_1_n
a_x_2_m
...