I know there are several topics about flattening lists and arrays. But I could not find an answer to my question in specific. I am trying to get all possible combinations of a matrix with a vector as follows:
import numpy as np
from itertools import product
Var1 = np.array([1,2,3])
Var2 = np.array([10,20,30])
Var3 = np.array([100,200,300])
Var4 = np.array([500,1000,1500])
First3Var = [Var1,Var2,Var3]
Combinations = list(product(First3Var, Var4))
This works fine, "Combinations" is almost what I want. However, I now get an array inside a list. I want it to be an array with 4 columns, not with 2. Does anyone know how I undo this nested array? I hope my question is clear. Thanks!
CodePudding user response:
You can do [np.append(i,j) for (i,j) in Combinations]
and use it as a list or as an np.array()
.
import numpy as np
from itertools import product
Var1 = np.array([1,2,3])
Var2 = np.array([10,20,30])
Var3 = np.array([100,200,300])
Var4 = np.array([500,1000,1500])
First3Var = [Var1,Var2,Var3]
Combinations = product(First3Var, Var4)
Combinations = np.array([np.append(i,j) for (i,j) in Combinations])
Now Combinations
is a 4-column matrix.
[[ 1 2 3 500]
[ 1 2 3 1000]
[ 1 2 3 1500]
[ 10 20 30 500]
[ 10 20 30 1000]
[ 10 20 30 1500]
[ 100 200 300 500]
[ 100 200 300 1000]
[ 100 200 300 1500]]