如果我有两个清单
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.
您还可以使用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。
| 归档时间: |
|
| 查看次数: |
10124 次 |
| 最近记录: |