是否有类似于R中的expand.grid()函数的Python函数?提前谢谢。
(编辑)下面是这个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 :(得分:24)
只需使用列表推导:
>>> [(x, y) for x in range(5) for y in range(5)]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]
如果需要,转换为numpy数组:
>>> import numpy as np
>>> x = np.array([(x, y) for x in range(5) for y in range(5)])
>>> x.shape
(25, 2)
我测试了高达10000 x 10000,python的性能与R中的expand.grid相当。使用元组(x,y)比使用列表[x,y]快40%左右理解。
要么...使用np.meshgrid大约快3倍,内存密集程度更低。
%timeit np.array(np.meshgrid(range(10000), range(10000))).reshape(2, 100000000).T
1 loops, best of 3: 736 ms per loop
R中的
> system.time(expand.grid(1:10000, 1:10000))
user system elapsed
1.991 0.416 2.424
请记住,R具有基于1的数组,而Python基于0。
答案 1 :(得分:17)
product
的 itertools
是解决方案的关键。它产生输入的笛卡尔积。
from itertools import product
def expand_grid(dictionary):
return pd.DataFrame([row for row in product(*dictionary.values())],
columns=dictionary.keys())
dictionary = {'color': ['red', 'green', 'blue'],
'vehicle': ['car', 'van', 'truck'],
'cylinders': [6, 8]}
>>> expand_grid(dictionary)
color cylinders vehicle
0 red 6 car
1 red 6 van
2 red 6 truck
3 red 8 car
4 red 8 van
5 red 8 truck
6 green 6 car
7 green 6 van
8 green 6 truck
9 green 8 car
10 green 8 van
11 green 8 truck
12 blue 6 car
13 blue 6 van
14 blue 6 truck
15 blue 8 car
16 blue 8 van
17 blue 8 truck
答案 2 :(得分:14)
这是一个示例,它提供类似于您需要的输出:
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
the rightmost element advances on every iteration中的事实有关。如果重要,可以通过巧妙地对product
列表进行排序来调整函数。
答案 3 :(得分:12)
我已经想了一段时间,我对目前提出的解决方案感到满意,所以我想出了自己的解决方案,这个方法相当简单(但可能更慢)。该函数使用numpy.meshgrid制作网格,然后将网格展平为1d数组并将它们放在一起:
def expand_grid(x, y):
xG, yG = np.meshgrid(x, y) # create the actual grid
xG = xG.flatten() # make the grid 1d
yG = yG.flatten() # same
return pd.DataFrame({'x':xG, 'y':yG}) # return a dataframe
例如:
import numpy as np
import pandas as pd
p, q = np.linspace(1, 10, 10), np.linspace(1, 10, 10)
def expand_grid(x, y):
xG, yG = np.meshgrid(x, y) # create the actual grid
xG = xG.flatten() # make the grid 1d
yG = yG.flatten() # same
return pd.DataFrame({'x':xG, 'y':yG})
print expand_grid(p, q).head(n = 20)
我知道这是一个老帖子,但我想我会分享我的简单版本!
答案 4 :(得分:8)
pandas documentation定义expand_grid
函数:
def expand_grid(data_dict):
"""Create a dataframe from every combination of given values."""
rows = itertools.product(*data_dict.values())
return pd.DataFrame.from_records(rows, columns=data_dict.keys())
要使此代码生效,您需要以下两个导入:
import itertools
import pandas as pd
输出为pandas.DataFrame
,这是Python中与R data.frame
最具可比性的对象。
答案 5 :(得分:6)
从上述解决方案中,我做到了
import itertools
import pandas as pd
a = [1,2,3]
b = [4,5,6]
ab = list(itertools.product(a,b))
abdf = pd.DataFrame(ab,columns=("a","b"))
以下是输出
a b
0 1 4
1 1 5
2 1 6
3 2 4
4 2 5
5 2 6
6 3 4
7 3 5
8 3 6
答案 6 :(得分:3)
这是另一个返回pandas.DataFrame:
的版本import itertools as it
import pandas as pd
def expand_grid(*args, **kwargs):
columns = []
lst = []
if args:
columns += xrange(len(args))
lst += args
if kwargs:
columns += kwargs.iterkeys()
lst += kwargs.itervalues()
return pd.DataFrame(list(it.product(*lst)), columns=columns)
print expand_grid([0,1], [1,2,3])
print expand_grid(a=[0,1], b=[1,2,3])
print expand_grid([0,1], b=[1,2,3])
答案 7 :(得分:0)
您是否尝试过product
的{{1}}?在我看来,比itertools
和pandas
除外一些方法更容易使用。请记住,此设置实际上将迭代器中的所有项目拉入列表,然后将其转换为meshgrid
,因此请注意更高的维度或删除ndarray
以获得更高维度的网格,除非您想要内存不足,您可以参考迭代器获取特定的组合。尽管如此我强烈推荐np.asarray(list(combs))
:
meshgrid
我从中得到以下输出:
#Generate square grid from axis
from itertools import product
import numpy as np
a=np.array(list(range(3)))+1 # axis with offset for 0 base index to 1
points=product(a,repeat=2) #only allow repeats for (i,j), (j,i) pairs with i!=j
np.asarray(list(points)) #convert to ndarray
答案 8 :(得分:0)
Scikit的ParameterGrid函数与expand_grid(R的)相同。 示例:
from sklearn.model_selection import ParameterGrid
grid = [{'kernel': ['linear']}, {'kernel': ['rbf'], 'gamma': [1, 10]}]
您可以访问将其转换为列表的内容:
list(ParameterGrid(grid))
输出:
[{'kernel': 'linear'},
{'gamma': 1, 'kernel': 'rbf'},
{'gamma': 10, 'kernel': 'rbf'}]
按索引访问元素
list(ParameterGrid(grid))[1]
您得到这样的东西:
{'gamma': 1, 'kernel': 'rbf'}
答案 9 :(得分:0)
这是任意数量的异构列类型的解决方案。它基于numpy.meshgrid
。 Thomas Browne的答案适用于同类列类型。内特的答案适用于两列。
import pandas as pd
import numpy as np
def expand_grid(*xi, columns=None):
"""Expand 1-D arrays xi into a pd.DataFrame
where each row is a unique combination of the xi.
Args:
x1, ..., xn (array_like): 1D-arrays to expand.
columns (list, optional): Column names for the output
DataFrame.
Returns:
Given vectors `x1, ..., xn` with lengths `Ni = len(xi)`
a pd.DataFrame of shape (prod(Ni), n) where rows are:
x1[0], x2[0], ..., xn-1[0], xn[0]
x1[1], x2[0], ..., xn-1[0], xn[0]
...
x1[N1 -1], x2[0], ..., xn-1[0], xn[0]
x1[0], x2[1], ..., xn-1[0], xn[0]
x1[1], x2[1], ..., xn-1[0], xn[0]
...
x1[N1 - 1], x2[N2 - 1], ..., xn-1[Nn-1 - 1], xn[Nn - 1]
"""
if columns is None:
columns = pd.RangeIndex(0, len(xi))
elif columns is not None and len(columns) != len(xi):
raise ValueError(
" ".join(["Expecting", str(len(xi)), "columns but",
str(len(columns)), "provided instead."])
)
return pd.DataFrame({
coln: arr.flatten() for coln, arr in zip(columns, np.meshgrid(*xi))
})
答案 10 :(得分:0)
the documentation的pyjanitor可以说是最自然的解决方案,尤其是如果您来自R背景。
用法是将others
参数设置为字典。词典中的项目可以具有不同的长度和类型。返回值是pandas DataFrame。
import janitor as jn
jn.expand_grid(others = {
'x': range(0, 4),
'y': ['a', 'b', 'c'],
'z': [False, True]
})