如果我有两个清单
l1 = [ 'A', 'B' ]
l2 = [ 1, 2 ]
获得pandas数据框的最优雅方式是什么,如下所示:
+-----+-----+-----+
| | l1 | l2 |
+-----+-----+-----+
| 0 | A | 1 |
+-----+-----+-----+
| 1 | A | 2 |
+-----+-----+-----+
| 2 | B | 1 |
+-----+-----+-----+
| 3 | B | 2 |
+-----+-----+-----+
注意,第一列是索引.
解决方法:
使用来自itertools的product
:
>>> 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