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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25634489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:25:11  来源:igfitidea点击:

Get all combinations of elements from two lists?

pythonpandas

提问by K.Chen

If I have two lists

如果我有两个列表

l1 = [ 'A', 'B' ]

l2 = [ 1, 2 ]

what is the most elegant way to get a pandas data frame which looks like:

获取如下所示的 Pandas 数据框的最优雅方法是什么:

+-----+-----+-----+
|     | l1  | l2  |
+-----+-----+-----+
|  0  | A   | 1   |
+-----+-----+-----+
|  1  | A   | 2   |
+-----+-----+-----+
|  2  | B   | 1   |
+-----+-----+-----+
|  3  | B   | 2   |
+-----+-----+-----+

Note, the first column is the index.

请注意,第一列是索引。

回答by behzad.nouri

use productfrom itertools:

使用productitertools

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

回答by Andy Hayden

As an alternative you can use pandas' cartesian_product(may be more useful with large numpy arrays):

作为替代方案,您可以使用 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

This seems a little messy to read in to a DataFrame with the correct orient...

以正确的方向读入 DataFrame 似乎有点混乱......

Note: previously cartesian_productwas located at pd.tools.util.cartesian_product.

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

回答by jpp

You can also use the sklearnlibrary, which uses a NumPy-based approach:

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

from sklearn.utils.extmath import cartesian

df = pd.DataFrame(cartesian((L1, L2)))

For more verbose but possibly more efficient variants see Numpy: cartesian product of x and y array points into single array of 2D points.

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