有没有类似于R中expand.grid()函数的Python函数?谢谢。
(EDIT) 以下是此R函数的描述和示例。
Create a Data Frame from All Combinations of Factors
Description:
Create a data frame from all combinations of the supplied vectors
or factors.
> x <- 1:3
> y <- 1:3
> expand.grid(x,y)
Var1 Var2
1 1 1
2 2 1
3 3 1
4 1 2
5 2 2
6 3 2
7 1 3
8 2 3
9 3 3
(EDIT2)以下是使用rpy包的示例。我想获取相同的输出对象,但不使用R:
>>> from rpy import *
>>> a = [1,2,3]
>>> b = [5,7,9]
>>> r.assign("a",a)
[1, 2, 3]
>>> r.assign("b",b)
[5, 7, 9]
>>> r("expand.grid(a,b)")
{'Var1': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'Var2': [5, 5, 5, 7, 7, 7, 9, 9, 9]}
编辑 02/09/2012: 我对Python感到非常困惑。Lev Levitsky在他的回答中提供的代码对我来说不起作用:
>>> a = [1,2,3]
>>> b = [5,7,9]
>>> expandgrid(a, b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in expandgrid
NameError: global name 'itertools' is not defined
然而itertools模块似乎已经安装了(输入from itertools import *
没有返回任何错误信息)
expand.grid
函数的摘要说明吗?甚至提供一个小例子会更好。 - GSeeitertools.product
实现应该不太难。 - Lev Levitskyexpand.grid
功能更加强大。我会用它来快速生成复杂因子水平的大型数组。因此,一些答案是针对解决(x, y)
输出情况而不是适用于任何n
个输入的情况。 - Hendyitertools.product
也适用于三个或更多向量。请参见我在 @Ahmed 的答案下的示例。 - Paul Rougieux