Looping through lists to create a cartesian product by row pandas

做~自己de王妃 提交于 2019-12-25 17:04:31

问题


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()

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


回答1:


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

itertools.product(*lst)


来源:https://stackoverflow.com/questions/59429879/looping-through-lists-to-create-a-cartesian-product-by-row-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!