有没有一个Python函数类似于R中的expand.grid()函数?提前谢谢。
下面是这个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]}
编辑2012年9月2日:我真的对Python迷路了。列夫·莱维斯基在他的回答中给出的密码对我不起作用:
>>> 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 *
不会返回任何错误消息)
只需使用列表理解:
如果需要,转换为numpy数组:
我已经测试了10000 x 10000,python的性能与R中的expand.grid相当。在理解中使用元组(x,y)比使用列表[x,y]快40%。
或者。。。使用np.meshgrid大约快3倍,内存占用更少。
在R中:
请记住,R有基于1的数组,而Python是基于0的。
来自
itertools
的product
是解决方案的关键。它产生输入的笛卡尔积。下面是一个示例,它提供了与您所需类似的输出:
这种差异与
itertools.product
the rightmost element advances on every iteration中的事实有关。如果列表很重要,可以通过对其进行智能排序来调整函数。相关问题 更多 >
编程相关推荐