简体   繁体   中英

Looping through lists to create a cartesian product by row 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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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