简体   繁体   English

在 python 中使用 itertools 进行组合

[英]Using itertools for combinations in python

I have the following table with 4 columns:我有下表,有 4 列:

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

My desired Output in a df:我在df中想要的Output:

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?使用 python 执行此操作的最佳方法是什么?

By table, I'm assuming that you just mean nested lists (also works with nested tuples or similar).按表格,我假设您只是指嵌套列表(也适用于嵌套元组或类似内容)。

import itertools

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

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:我假设你的表是指 pandas dataframe,所以第一步是将感兴趣的列收集到列表中:

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:最后使用itertools推导出这些列表的乘积:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM