I have two numpy arrays that define the x and y axes of a grid. For example:
JavaScript
x
3
1
x = numpy.array([1,2,3])
2
y = numpy.array([4,5])
3
I’d like to generate the Cartesian product of these arrays to generate:
JavaScript
1
2
1
array([[1,4],[2,4],[3,4],[1,5],[2,5],[3,5]])
2
In a way that’s not terribly inefficient since I need to do this many times in a loop. I’m assuming that converting them to a Python list and using itertools.product
and back to a numpy array is not the most efficient form.
Advertisement
Answer
JavaScript
1
8
1
>>> numpy.transpose([numpy.tile(x, len(y)), numpy.repeat(y, len(x))])
2
array([[1, 4],
3
[2, 4],
4
[3, 4],
5
[1, 5],
6
[2, 5],
7
[3, 5]])
8
See Using numpy to build an array of all combinations of two arrays for a general solution for computing the Cartesian product of N arrays.