在python中使用itertools进行组合



我有以下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最好的方法是什么?

我假设这里的表指的是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
...

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

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

最新更新