matthew
matthew

Reputation: 157

All possible combinations of elements of three vectors in Python

I have three lists, each containing lets say 2 elements. How can I obtain a (8x3) array which contains all the possible combinations (with replacement) of the elements in the three lists?

Example:

vec1 = [4, 6]
vec2 = [2, 4]
vec3 = [1, 5]

output = [[4, 2, 1], [4, 2, 5], [4, 4, 1], [4, 4, 5], [6, 2, 1], [6, 4, 5], [6, 2, 5], [6, 4, 1]]

This is my code (simplified):

import scipy.stats as st
percentiles = [0.01, 0.99]
draws1 = st.norm.ppf(percentiles, 0, 1)
draws2 = st.norm.ppf(percentiles, 0, 1)
draws3 = st.norm.ppf(percentiles, 0, 1)

Upvotes: 2

Views: 816

Answers (2)

Arraval
Arraval

Reputation: 1130

You can use simple for loops:

import numpy as np
vec1 = [4, 6]
vec2 = [2, 4]
vec3 = [1, 5]

output = np.zeros([8,3])
counter = 0
for i in vec1:
    for j in vec2:
        for k in vec3:
            temp = [i,j,k]
            output[counter,:] = [i,j,k]
            counter += 1

Upvotes: 0

lemac
lemac

Reputation: 223

You could use numpy.meshgrid() like so:

np.array(np.meshgrid([4, 6], [2, 4], [1, 5])).T.reshape(-1,3)

Which results in:

 array([[4, 2, 1],
       [4, 4, 1],
       [6, 2, 1],
       [6, 4, 1],
       [4, 2, 5],
       [4, 4, 5],
       [6, 2, 5],
       [6, 4, 5]])

Upvotes: 2

Related Questions