w3resource

NumPy: Build an array of all combinations of three NumPy arrays

NumPy: Array Object Exercise-113 with Solution

Write a NumPy program to build an array of all combinations of three NumPy arrays.

Sample Solution:

Python Code:

import numpy as np
x = [1, 2, 3]
y = [4, 5]
z = [6, 7]
print("Original arrays:")
print("Array-1")
print(x)
print("Array-2")
print(y)
print("Array-3")
print(z)
new_array = np.array(np.meshgrid(x, y, z)).T.reshape(-1,3)
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]]

Python Code Editor:

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

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