NumPy: Build an array of all combinations of three NumPy arrays
NumPy: Array Object Exercise-113 with Solution
Build Array of All Combinations of Three Arrays
Write a NumPy program to build an array of all combinations of three NumPy arrays.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating three lists: 'x', 'y', and 'z'
x = [1, 2, 3]
y = [4, 5]
z = [6, 7]
# Printing the original arrays
print("Original arrays:")
print("Array-1")
print(x)
print("Array-2")
print(y)
print("Array-3")
print(z)
# Creating a new NumPy array by meshgrid to combine elements from 'x', 'y', and 'z'
new_array = np.array(np.meshgrid(x, y, z)).T.reshape(-1, 3)
# Printing the combined array obtained from meshgrid
print("Combine array:")
print(new_array)
Sample Output:
Original arrays: Array-1 [1, 2, 3] Array-2 [4, 5] Array-3 [6, 7] Combine array: [[1 4 6] [1 5 6] [2 4 6] [2 5 6] [3 4 6] [3 5 6] [1 4 7] [1 5 7] [2 4 7] [2 5 7] [3 4 7] [3 5 7]]
Explanation:
In the above code –
- x = [1, 2, 3]: Define the first list 'x' with elements 1, 2, and 3.
- y = [4, 5]: Define the second list 'y' with elements 4 and 5.
- z = [6, 7]: Define the third list 'z' with elements 6 and 7.
- np.meshgrid(x, y, z): Create a meshgrid from the input lists 'x', 'y', and 'z'. The meshgrid is a multidimensional grid that contains the coordinates of all possible combinations of elements from the input lists.
- np.array(np.meshgrid(x, y, z)).T: Transpose the meshgrid to rearrange the axes.
- .reshape(-1, 3): Reshape the transposed array into a 2D array with 3 columns and an automatically calculated number of rows.
- new_array = ...: Assign the reshaped array to the variable 'new_array'.
- Finally print() function prints the resulting 'new_array' containing all possible combinations of elements from lists 'x', 'y', and 'z'.
Python-Numpy Code Editor:
Previous: Write a NumPy program to get the memory usage by NumPy arrays.
Next: Write a NumPy program to create random set of rows from 2D array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-113.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics