Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a numpy arrays of all possible combinations of elements

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)])]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading