Search code examples
pythonnumpycartesian-product

Cartesian product of x and y array points into single array of 2D points


I have two numpy arrays that define the x and y axes of a grid. For example:

x = numpy.array([1,2,3])
y = numpy.array([4,5])

I'd like to generate the Cartesian product of these arrays to generate:

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

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.


Solution

  • >>> numpy.transpose([numpy.tile(x, len(y)), numpy.repeat(y, len(x))])
    array([[1, 4],
           [2, 4],
           [3, 4],
           [1, 5],
           [2, 5],
           [3, 5]])
    

    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.