Let say I have 2 numpy
arrays
import numpy as np
x = np.array([1,2,3])
y = np.array([1,2,3,4])
With this, I want to create a 2-dimensional array as below
Is there any method available to directly achieve this?
CodePudding user response:
You problem is about writing the Cartesian product. In numpy, you can write it using repeat
and tile
:
out = np.c_[np.repeat(x, len(y)), np.tile(y, len(x))]
Python's builtin itertools
module has a method designed for this: product
:
from itertools import product
out = np.array(list(product(x,y)))
Output:
array([[1, 1],
[1, 2],
[1, 3],
[1, 4],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[3, 1],
[3, 2],
[3, 3],
[3, 4]])