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 –
- x = np.array([1,2,3]): This line creates a 1D NumPy array 'x' containing the elements [1, 2, 3].
- y = np.array([4,5]): This line creates a 1D NumPy array 'y' containing the elements [4, 5].
- 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].
- 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].
- 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 Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics