I would like to creare a Numpy array, which consists of all possible combinations. I have a number of samples, which may have a set of possible values. Currently I use recursion, but am looking for faster methods to work with a high number of combinations. A possible number of combinations is (n of values)^samples
import numpy as np
import itertools
samples=3
range1=range(1)
range2=range(20,101,10)
a=np.zeros((samples))
total=np.empty((0,samples))
limit=1000
def nested(samples,limit):
if samples>0:
for j in itertools.chain(range1, range2):
a[samples-1]=j
global total
total=np.vstack((total,a))
nested(samples-1,limit)
nested(samples, limit)
total=np.unique(total, axis=0)
print(total.shape)
With currently applied recursion method, it takes a lot of time to build an array with 1M combinations.
CodePudding user response:
You can use itertools.product()
for this:
samples = 3
values = list(itertools.chain(range1, range2)) # all iterables
total = [list(item) for item in itertools.product(*[values for _ in range(samples)])]