w3resource

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


Create Cartesian Product of Two Arrays

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

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' containing integers [1, 2, 3]
x = np.array([1, 2, 3])

# Creating a NumPy array 'y' containing integers [4, 5]
y = np.array([4, 5])

# Using np.tile and np.repeat to create a grid of repeated elements from 'x' and 'y'
# The grid is created by replicating 'x' along rows and 'y' along columns
result = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])

# Printing the resulting grid obtained by combining 'x' and 'y' elements
print(result) 

Sample Output:

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

Explanation:

In the above code –

  1. x = np.array([1,2,3]): This line creates a 1D NumPy array 'x' containing the elements [1, 2, 3].
  2. y = np.array([4,5]): This line creates a 1D NumPy array 'y' containing the elements [4, 5].
  3. np.tile(x, len(y)): Repeat the elements of 'x' as many times as there are elements in 'y'. In this case, 'x' will be repeated twice, resulting in the array [1, 2, 3, 1, 2, 3].
  4. np.repeat(y, len(x)): Repeat each element of 'y' as many times as there are elements in 'x'. In this case, each element of 'y' will be repeated three times, resulting in the array [4, 4, 4, 5, 5, 5].
  5. np.transpose(...): Combine the arrays from steps 3 and 4 by stacking them along a new axis and then transposing the result. This gives the final 2D array 'result', which contains all possible combinations of elements from 'x' and 'y':

Pictorial Presentation:

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

For more Practice: Solve these Related Problems:

  • Write a NumPy program to compute the Cartesian product of two 1D arrays using np.meshgrid and reshape.
  • Create a function that returns a 2D array of all possible pairs formed from two input arrays.
  • Test the Cartesian product function with arrays of different lengths and verify the resulting shape.
  • Implement the solution using np.column_stack to combine flattened meshgrid outputs.

Python-Numpy Code Editor:

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 Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.