从两个列表中获取元素的所有组合? [英] Get all combinations of elements from two lists?
本文介绍了从两个列表中获取元素的所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有两个列表
l1 = [ 'A', 'B' ]
l2 = [ 1, 2 ]
什么是获取如下所示的熊猫数据框的最优雅的方式?
what is the most elegant way to get a pandas data frame which looks like:
+-----+-----+-----+
| | l1 | l2 |
+-----+-----+-----+
| 0 | A | 1 |
+-----+-----+-----+
| 1 | A | 2 |
+-----+-----+-----+
| 2 | B | 1 |
+-----+-----+-----+
| 3 | B | 2 |
+-----+-----+-----+
请注意,第一列是索引.
Note, the first column is the index.
推荐答案
使用 product
来自itertools
:
>>> from itertools import product
>>> pd.DataFrame(list(product(l1, l2)), columns=['l1', 'l2'])
l1 l2
0 A 1
1 A 2
2 B 1
3 B 2
这篇关于从两个列表中获取元素的所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文