w3resource

NumPy: Create a Cartesian product of two arrays into single array of 2D points

NumPy: Array Object Exercise-111 with Solution

Write a NumPy program to create a Cartesian product of two arrays into single array of 2D points.

Sample Solution:

Python Code:

import numpy as np
x = np.array([1,2,3])
y = np.array([4,5])
result = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])
print(result)

Sample Output:

[[1 4]
 [2 4]
 [3 4]
 [1 5]
 [2 5]
 [3 5]]

Pictorial Presentation:

Python NumPy: Create a Cartesian product of two arrays into single array of 2D points

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to remove nan values from an given array.
Next: Write a NumPy program to get the memory usage by numpy arrays.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}