遍历列表以按行 pandas 创建笛卡尔积 [英] Looping through lists to create a cartesian product by row pandas

查看:74
本文介绍了遍历列表以按行 pandas 创建笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过乘积在多个列表中扩展行.我当前使用的逻辑是:

I'd like to expand my rows by their cross product across multiple lists. The current logic I use is:

list = [['Yes', 'No', 'Maybe'], ['Yes', 'No', 'Maybe']]
    index = pd.MultiIndex.from_product(list, names = ["column1", "column2"])
    pd.DataFrame(index = index).reset_index()

不幸的是,它不能用于多个列表.我将如何运行如下所示的笛卡尔乘积: [[['是','否','也许'],['是','否','也许']],[['是','否','也许'],['是' ,否",也许"]]] 仍然只让它们运行两列.我希望产生18(2 *(3 ^ 2))的叉积.

which unfortunately will not work for more than one list. How would I be able to run the cartesian product of something that looks like this: [[['Yes', 'No', 'Maybe'], ['Yes', 'No', 'Maybe']],[['Yes', 'No', 'Maybe'], ['Yes', 'No', 'Maybe']]] and still have them only run for two columns. I'm looking to produce a crossproduct of 18 (2 * (3 ^ 2)).

推荐答案

itertools.product 允许您从任意数量的可迭代对象创建笛卡尔乘积:

itertools.product allows you to create a cartesian product from an arbitrary number of iterables:

itertools.product(*lst)

这篇关于遍历列表以按行 pandas 创建笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆