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

Question

Asked By – Rich

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.

Now we will see solution for issue: Cartesian product of x and y array points into single array of 2D points


Answer

>>> 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.

This question is answered By – kennytm

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0