我有一个如下所示的n维数组:
np.array([[0,3],[0,3],[0,10]])
在这个数组中,元素表示低值和高值。例如:
[0,3]
表示 [0,1,2,3]
。我需要使用上述给定的范围生成所有值的组合。例如,我想要
[0,0,0], [0,0,1] ... [0,1,0] ... [3,3,10]
。我尝试了以下方法来得到我想要的结果:
ds = np.array([[0,3],[0,3],[0,10]])
nItems = int(reduce(lambda a,b: a * (b[1] - b[0] + 1), ds, 1))
myCombinations = np.zeros((nItems,))
nArrays = []
for x in range(ds.shape[0]):
low = ds[x][0]
high= ds[x][1]
nitm = high - low + 1
ar = [x+low for x in range(nitm) ]
nArrays.append(ar)
myCombinations = cartesian(nArrays)
这个笛卡尔函数取自于使用numpy构建两个数组的所有组合的数组
我需要执行这个操作几百万次。
我的问题是:有没有更好/更有效的方法来做到这一点?
itertools.product
实际运行速度约快 6 倍。我的方法大部分时间都被mgrid
占用,所以您甚至不能通过避免使用rollaxis
和reshape
来加快它。出于好奇,您使用的 Python 和 numpy 版本是什么? - Praveenrollaxis
+reshape
效果的另一种方法,但在此过程中失去了numpy的特性,那就是使用zip(a[0].flatten(), a[1].flatten(), a[2].flatten())
。 - Praveen