有条件的字典的笛卡尔积

Cartesian product of dictionnaries with a condition

我目前正在尝试执行网格搜索来优化函数。不幸的是,计算时间太长了,这主要是由于我的网格搜索中无用的计算。到目前为止,我只尝试做一个笛卡尔积,它给我的参数集比我需要的多。

我有以下输入:

dict_params = {"params_a": [0, 1],
               "params_b": ["x1", "x2", "x3"],
               "params_c": {"x1": ["a1", "a2"],
                            "x2": ["b1", "b2"],
                            "x3": ["c1", "c2"]
                           }
               }

我希望得到以下输出:

output_expected = [{"params_a" : 0, "params_b" : "x1", "params_c": "a1"},
                   {"params_a" : 0, "params_b" : "x1", "params_c": "a2"},
                   {"params_a" : 0, "params_b" : "x2", "params_c": "b1"},
                   {"params_a" : 0, "params_b" : "x2", "params_c": "b2"},
                   {"params_a" : 0, "params_b" : "x3", "params_c": "c1"},
                   {"params_a" : 0, "params_b" : "x3", "params_c": "c2"},
                   {"params_a" : 1, "params_b" : "x1", "params_c": "a1"},
                   {"params_a" : 1, "params_b" : "x1", "params_c": "a2"},
                   {"params_a" : 1, "params_b" : "x2", "params_c": "b1"},
                   {"params_a" : 1, "params_b" : "x2", "params_c": "b2"},
                   {"params_a" : 1, "params_b" : "x3", "params_c": "c1"},
                   {"params_a" : 1, "params_b" : "x3", "params_c": "c2"}
                  ]

返回的任何格式都可以。我试图用完整的笛卡尔积填充数据框,然后合并到“params_b”=“params_c”,不幸的是我无法让它工作。

感谢阅读

我看到的一种使用方式 pandas:

(pd.DataFrame(product(dict_params['params_a'], dict_params['params_b']),
              columns=['params_a', 'params_b'])
   .assign(params_c=lambda d: d['params_b'].map(pd.Series(dict_params['params_c'])))
   .explode('params_c')
)

输出:

   params_a params_b params_c
0         0       x1       a1
0         0       x1       a2
1         0       x2       b1
1         0       x2       b2
2         0       x3       c1
2         0       x3       c2
3         1       x1       a1
3         1       x1       a2
4         1       x2       b1
4         1       x2       b2
5         1       x3       c1
5         1       x3       c2

使用本机 python 你可以这样做 :

dict_params = {"a": [0, 1],
        "b": ["x1", "x2", "x3"],
        "c": {"x1": ["a1", "a2"],
                    "x2": ["b1", "b2"],
                    "x3": ["c1", "c2"]
                    }
        }

res = []

for param_a in dict_params['a']:
    for param_b in dict_params['b']:
        for param_c in dict_params['c'][param_b]:
            res.append({'a': param_a, 'b': param_b, 'c': param_c})

print(res)