R Python中的expand.grid()函数

发布于 2021-01-29 18:40:50

是否有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]}

编辑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 *不会返回任何错误消息)

关注者
0
被浏览
53
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这是一个提供与您所需输出类似的示例:

    import itertools
    def expandgrid(*itrs):
       product = list(itertools.product(*itrs))
       return {'Var{}'.format(i+1):[x[i] for x in product] for i in range(len(itrs))}
    
    >>> a = [1,2,3]
    >>> b = [5,7,9]
    >>> expandgrid(a, b)
    {'Var1': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'Var2': [5, 7, 9, 5, 7, 9, 5, 7, 9]}
    

    差异与以下事实有关:在itertools.product
    最右边的元素在每次迭代中都会前进product如果重要,您可以通过巧妙地对列表进行排序来调整功能。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看