从两个列表中获取所有元素组合?

K.C*_*hen 16 python pandas

如果我有两个清单

l1 = [ 'A', 'B' ]

l2 = [ 1, 2 ]
Run Code Online (Sandbox Code Playgroud)

获得pandas数据框的最优雅方式是什么,如下所示:

+-----+-----+-----+
|     | l1  | l2  |
+-----+-----+-----+
|  0  | A   | 1   |
+-----+-----+-----+
|  1  | A   | 2   |
+-----+-----+-----+
|  2  | B   | 1   |
+-----+-----+-----+
|  3  | B   | 2   |
+-----+-----+-----+
Run Code Online (Sandbox Code Playgroud)

注意,第一列是索引.

beh*_*uri 29

使用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
Run Code Online (Sandbox Code Playgroud)


And*_*den 11

作为替代方案,您可以使用pandas' cartesian_product(对于大型numpy数组可能更有用):

In [11]: lp1, lp2 = pd.core.reshape.util.cartesian_product([l1, l2])

In [12]: pd.DataFrame(dict(l1=lp1, l2=lp2))
Out[12]:
  l1  l2
0  A   1
1  A   2
2  B   1
3  B   2
Run Code Online (Sandbox Code Playgroud)

阅读具有正确方向的DataFrame看起来有点混乱......

注意:以前cartesian_product位于pd.tools.util.cartesian_product.

  • 从pandas 0.20.2开始,`cartesian_product()`在`pd.core.reshape.util`中.这个解决方案比使用`itertools.product`更快,并且可以通过使用非解压缩数据的`np.array().T`初始化数据帧来加快速度. (3认同)

jpp*_*jpp 5

您还可以使用sklearn使用基于 NumPy 的方法的库:

from sklearn.utils.extmath import cartesian

df = pd.DataFrame(cartesian((L1, L2)))
Run Code Online (Sandbox Code Playgroud)

有关更详细但可能更有效的变体,请参阅Numpy: cartesian product of x and y array points into single array of 2D points